Power Hour Trendlines [LuxAlgo]The Power Hour Trendlines indicator is based on Power Hours detection, and includes up to three displayed trendlines derived from the closing prices of all the bars within the last user-selected Power Hours.
Users can edit the time of Power Hours, choose how many sessions to take into account, enable or disable any trendlines, and change their colors.
🔶 USAGE
The Power Hour is defined as the last hour of the trading session and is set by default from 3:00 p.m. to 4:00 p.m. New York time. During this period, volume and volatility enter the market. Traders using higher timeframes may use this period to enter or exit positions by placing MOC (Market on Close) orders.
This tool works under the hypothesis that prices made during power hours (periods with high trading activity) are more relevant when used for the construction of trendlines.
An initial trendline is fit using linear regression; prices from power hours located above this initial fit are used for the upper trendline, while the ones below the fit are used for the lower one.
As with any trendline, traders can analyze the slope to determine the market's direction:
Positive slope: The market is trending up.
Negative slope: The market is trending down.
No slope: The market is trending sideways.
As we can see in the image, Nasdaq and Bitcoin are clearly in downtrends, gold is clearly in an uptrend, and the euro/U.S. dollar is in a sideways market over the last visible sessions.
As you can see, the trend lines may or may not be parallel to each other. The wider the area, the more volatile the data. The narrower the area, the less volatile the data. Let's look at an example.
In the image, the Dow30 and the euro/U.S. dollar have opposite behaviors. The volatility above the middle trendline is growing in the first case but shrinking in the second. In both cases, the volatility in the bottom area seems steady, so there are no big surprises there.
Traders can adjust the number of sessions for calculations, making the tool ideal for analyzing price behavior over different time frames.
As the image shows, we can clearly see how the market behaves over different time periods. XLY has been moving down over the last 10, 20, and 40 sessions, with a steeper decline over shorter periods. However, it has been moving sideways over the last 70 sessions.
One of the main uses of trendlines is to provide key support and resistance. In the image, SPY is shown with trendlines over the last 20 sessions. These lines provide excellent reference points for trading and observing price behavior in those areas, such as whether prices are accepted or rejected, which may trigger a response from other traders.
🔹 Not Allowed Timeframes
For obvious reasons, timeframes larger than 1H are not allowed. The Power Hour is defined as the last hour of the trading session. The tool will display a warning message if the timeframe is longer than 60 minutes.
🔶 SETTINGS
Power Hour (NY Time): Choose a custom Power Hour in New York time
Sessions Memory: Select how many Power Hours to take into account for calculations.
🔹 Style
Top: Enable or disable the top line and choose the line and background colors.
Middle: Enable or disable the middle line and choose the line color.
Bottom: Enable or disable the bottom line and choose the line and background colors.
Background: Enable or disable the background color for top and bottom lines.
Indicadores e estratégias
Volatility Regimes | GainzAlgo📊 OVERVIEW:
=========
This is a comprehensive ATR-based trading system designed for professional
traders who need advanced volatility analysis, precise trade management, and
intelligent market regime detection. The indicator combines multiple proven
volatility concepts into one powerful, customizable tool.
⭐ WHY THIS SYSTEM IS UNIQUE AND WORTHY OF PUBLICATION:
====================================================
This is not simply a collection of ATR-based indicators placed together.
It represents a unified volatility analysis framework where each component
is specifically designed to work in concert with the others, creating a
complete trading workflow that cannot be replicated by using multiple
separate indicators.
🔗 SYNERGISTIC INTEGRATION - How Components Work Together:
🧠 1. CONTEXT-AWARE ANALYSIS
The Volatility Regime Detection acts as the "brain" of the system,
classifying market conditions into 4 distinct phases. Every other
component then adapts its behavior based on this regime classification:
- ATR Bands expand/contract with regime changes
- Stop Loss distances automatically adjust (tighter in compression,
wider in high volatility)
- Take Profit targets scale proportionally to current regime
- Signal sensitivity filters itself based on market phase
📐 2. UNIFIED VOLATILITY FOUNDATION
All calculations share a single ATR baseline calculation, ensuring
internal consistency across the entire system. When ATR changes, every
element updates in perfect synchronization:
- Bands recalculate from the same ATR value
- Risk management levels use the same volatility measurement
- Regime classification and signals reference identical data
🛡️ 3. INTEGRATED RISK MANAGEMENT
The system doesn't just show WHERE to enter - it calculates HOW MUCH
to risk:
- Dynamic Stop Loss adapts to current ATR automatically
- Position Size Calculator uses the dynamic stop to compute exact quantities
- Take Profit levels scale proportionally, maintaining optimal risk:reward
✅ 4. TWO-STAGE SIGNAL CONFIRMATION
The alert system creates a logical progression:
Step 1: Volatility Breakout → Market energy is building
Step 2: Trend Confirmation → Direction confirmed with volatility support
This prevents false breakouts by requiring both volatility AND direction.
🏦 5. PROFESSIONAL WORKFLOW INTEGRATION
The system mirrors how institutional traders analyze markets:
Phase 1: Assess regime → What's the market doing?
Phase 2: Identify setup → Where's the opportunity?
Phase 3: Calculate risk → What's my exposure?
Phase 4: Set targets → Where do I take profit?
Phase 5: Monitor regime → When do conditions change?
❌ WHY NOT USE SEPARATE INDICATORS?
- Separate ATR Bands: Don't know about regime changes, remain static
- Separate Regime Indicator: Doesn't automatically adjust stop/targets
- Separate Position Calculator: Doesn't know your actual ATR-based stop
- Manual Integration: Requires constant mental calculation and cross-referencing
🧮 DETAILED CALCULATION METHODOLOGY:
=================================
📏 ATR (AVERAGE TRUE RANGE) CALCULATION:
- True Range = Maximum of:
1. Current High - Current Low
2. Absolute value of (Current High - Previous Close)
3. Absolute value of (Current Low - Previous Close)
- ATR = Simple Moving Average of True Range over specified period (default: 14)
📊 DYNAMIC ATR BANDS:
- Upper Band = Current Close + (ATR × Band Multiplier)
- Lower Band = Current Close - (ATR × Band Multiplier)
- Band 1: 1.0× ATR (closest support/resistance)
- Band 2: 2.0× ATR (intermediate zone)
- Band 3: 3.0× ATR (extended zone)
🌡️ VOLATILITY REGIME CLASSIFICATION:
Step 1: Calculate ATR Baseline
- Baseline ATR = SMA or EMA of ATR over long period (default: 50 bars)
- This represents "normal" volatility for the instrument
Step 2: Calculate ATR Ratio
- ATR Ratio = Current ATR ÷ Baseline ATR
- Example: If current ATR = 70 and baseline = 50, ratio = 1.40
Step 3: Classify Regime Based on Ratio
- COMPRESSION: Ratio < 0.70 (ATR is 30% below normal)
Market consolidating, volatility contracting, energy building
- EXPANSION: Ratio between 1.15 and 1.40 (ATR is 15-40% above normal)
Volatility breaking out, early phase of directional movement
- HIGH VOLATILITY: Ratio > 1.40 (ATR is 40%+ above normal)
Strong sustained trend with high participation
- EXHAUSTION: ATR declining after high volatility period
Requires: Previous high ratio + declining ATR over X bars (default: 5)
Trend maturity, potential reversal or consolidation approaching
🛑 DYNAMIC STOP LOSS CALCULATION:
- For Long Positions: Stop Loss = Entry Price - (ATR × SL Multiplier)
- For Short Positions: Stop Loss = Entry Price + (ATR × SL Multiplier)
- Default Multiplier: 2.0× ATR
- Adjusts automatically: Wider in high volatility, tighter in compression
🎯 TAKE PROFIT LEVELS:
- TP1 = Entry Price ± (ATR × TP1 Multiplier)
- TP2 = Entry Price ± (ATR × TP2 Multiplier)
- TP3 = Entry Price ± (ATR × TP3 Multiplier)
- Direction (+ or -) depends on trade direction
📦 POSITION SIZE CALCULATION:
Formula: Position Size = Account Risk Amount ÷ Stop Loss Distance
Step-by-step:
1. Risk Amount = Account Size × (Risk Percentage ÷ 100)
2. Stop Distance = |Entry Price - Stop Loss Price|
3. Position Size = Risk Amount ÷ Stop Distance
📈 ATR PERCENTILE RANKING:
- >80% = Extremely high volatility
- 20-80% = Normal volatility range
- <20% = Extremely low volatility
🌀 VOLATILITY CONTRACTION PATTERN:
Detects extended low-volatility periods indicating imminent breakout.
🧭 TREND DETECTION SIGNALS:
Bullish: Price > MA AND Current ATR > ATR MA
Bearish: Price < MA AND Current ATR > ATR MA
⚡ VOLATILITY BREAKOUT SIGNALS:
Triggered when ATR exceeds its moving average by a defined threshold.
🧩 CORE FEATURES:
==============
1. ATR BANDS (Dynamic Support/Resistance)
2. VOLATILITY REGIME DETECTION
3. DYNAMIC STOP LOSS SYSTEM
4. MULTIPLE TAKE PROFIT LEVELS
5. SUPPORT & RESISTANCE LEVELS
6. RISK MANAGEMENT CALCULATOR
7. ATR PERCENTILE RANKING
8. VOLATILITY CONTRACTION PATTERN
9. TREND DETECTION SIGNALS
10. VOLATILITY BREAKOUT SIGNALS
⚙️ RECOMMENDED SETTINGS BY TRADING STYLE:
======================================
DAY TRADING • SWING TRADING • POSITION TRADING • SCALPING
📘 HOW TO USE THIS INDICATOR:
==========================
STEP 1: Identify Market Regime
STEP 2: Wait for Entry Signal
STEP 3: Set Stop Loss
STEP 4: Set Take Profits
STEP 5: Position Sizing
STEP 6: Monitor & Manage
🔔 ALERT SYSTEM:
=============
Alerts for volatility breakouts, trend changes, regime transitions,
ATR band crossings, contraction completion, and percentile extremes.
🎨 CUSTOMIZATION:
==============
All visuals, thresholds, multipliers, colors, alerts, and risk parameters
can be fully customized.
⚠️ IMPORTANT DISCLAIMER:
=====================
This indicator is a volatility analysis tool and does NOT provide financial advice.
Past performance does not guarantee future results.
All trading involves substantial risk.
All trading decisions are the sole responsibility of the user.
Volume-Weighted Price Z-Score [QuantAlgo]🟢 Overview
The Volume-Weighted Price Z-Score indicator quantifies price deviations from volume-weighted equilibrium using statistical standardization. It combines volume-weighted moving average analysis with logarithmic deviation measurement and volatility normalization to identify when prices have moved to statistically extreme levels relative to their volume-weighted baseline, helping traders and investors spot potential mean reversion opportunities across multiple timeframes and asset classes.
🟢 How It Works
The indicator's core methodology lies in its volume-weighted statistical approach, where price displacement is measured through normalized deviations from volume-weighted price levels:
volumeWeightedAverage = ta.vwma(priceSource, lookbackPeriod)
logDeviation = math.log(priceSource / volumeWeightedAverage)
volatilityMeasure = ta.stdev(logDeviation, lookbackPeriod)
The script uses logarithmic transformation to capture proportional price changes rather than absolute differences, ensuring equal treatment of percentage moves regardless of price level:
rawZScore = logDeviation / volatilityMeasure
zScore = ta.ema(rawZScore, smoothingPeriod)
First, it establishes the volume-weighted baseline which gives greater weight to price levels where significant trading occurred, creating a more representative equilibrium point than simple moving averages.
Then, the logarithmic deviation measurement converts the price-to-average ratio into a normalized scale:
logDeviation = math.log(priceSource / volumeWeightedAverage)
Next, statistical normalization is achieved by dividing the deviation by its own historical volatility, creating a standardized z-score that measures how many standard deviations the current price sits from the volume-weighted mean.
Finally, EMA smoothing filters noise while preserving the signal's responsiveness to genuine market extremes:
rawZScore = logDeviation / volatilityMeasure
zScore = ta.ema(rawZScore, smoothingPeriod)
This creates a volume-anchored statistical oscillator that combines price-volume relationship analysis with volatility-adjusted normalization, providing traders with probabilistic insights into market extremes and mean reversion potential based on standard deviation thresholds.
🟢 Signal Interpretation
▶ Positive Values (Above Zero): Price trading above volume-weighted average indicating potential overvaluation relative to volume-weighted equilibrium = Caution on longs, potential mean reversion downward = Short/sell opportunities
▶ Negative Values (Below Zero): Price trading below volume-weighted average indicating potential undervaluation relative to volume-weighted equilibrium = Caution on shorts, potential mean reversion upward = Long/buy opportunities
▶ Zero Line Crosses: Mean reversion transitions where price crosses back through volume-weighted equilibrium, indicating shift from overvalued to undervalued (or vice versa) territory
▶ Extreme Positive Zone (Above +2.5σ default): Statistically rare overvaluation representing 98.8%+ confidence level deviation, indicating extremely stretched bullish conditions with high mean reversion probability = Strong correction warning/short signal
▶ Extreme Negative Zone (Below -2.5σ default): Statistically rare undervaluation representing 98.8%+ confidence level deviation, indicating extremely stretched bearish conditions with high mean reversion probability = Strong buying opportunity signal
▶ ±1σ Reference Levels: Moderate deviation zones (±1 standard deviation) marking common price fluctuation boundaries where approximately 68% of price action occurs under normal distribution
▶ ±2σ Reference Levels: Significant deviation zones (±2 standard deviations) marking unusual price extremes where approximately 95% of price action should be contained under normal conditions
🟢 Features
▶ Preconfigured Presets: Three optimized parameter sets accommodate different analytical approaches, instruments and timeframes. "Default" provides balanced statistical measurement suitable for swing trading and daily/4-hour analysis, offering deviation detection with moderate responsiveness to price dislocations. "Fast Response" delivers heightened sensitivity optimized for intraday trading and scalping on 15-minute to 1-hour charts, using shorter statistical windows and minimal smoothing to capture rapid mean reversion opportunities as they develop. "Smooth Trend" offers conservative extreme identification ideal for position trading on daily to weekly charts, employing extended statistical periods and heavy noise filtering to isolate only the most significant market extremes.
▶ Built-in Alerts: Seven alert conditions enable comprehensive automated monitoring of statistical extremes and mean reversion events. Extreme Overbought triggers when z-score crosses above the extreme threshold (default +2.5σ) signaling rare overvaluation, Extreme Oversold activates when z-score crosses below the negative extreme threshold (default -2.5σ) signaling rare undervaluation. Exit Extreme Overbought and Exit Extreme Oversold alert when prices begin reverting from these statistical extremes back toward the mean. Bullish Mean Reversion notifies when z-score crosses above zero indicating shift to overvalued territory, while Bearish Mean Reversion triggers on crosses below zero indicating shift to undervalued territory. Any Extreme Level provides a combined alert for any extreme threshold breach regardless of direction. These notifications allow you to capitalize on statistically significant price dislocations without continuous chart monitoring.
▶ Color Customization: Six visual themes (Classic, Aqua, Cosmic, Ember, Neon, plus Custom) accommodate different chart backgrounds and visual preferences, ensuring optimal contrast for identifying positive versus negative deviations across trading environments. The adjustable fill transparency control (0-100%) allows fine-tuning of the gradient area prominence between the z-score line and zero baseline, with higher opacity values creating subtle background context while lower values produce bold deviation emphasis. Optional bar coloring extends the z-score gradient directly to the indicator pane bars, providing immediate visual reinforcement of current deviation magnitude and direction without requiring reference to the plotted line itself.
*Note: This indicator requires volume data to function correctly, as it calculates deviations from a volume-weighted price average. Tickers with no volume data or extremely limited volume will not produce meaningful results, i.e., the indicator may display flat lines, erratic values, or fail to calculate properly. Using this indicator on assets without volume data (certain forex pairs, synthetic indices, or instruments with unreported/unavailable volume) will produce unreliable or no results at all. Additionally, ensure your chart has sufficient historical data to cover the selected lookback period, e.g., using a 100-bar lookback on a chart with only 50 bars of history will yield incomplete or inaccurate calculations. Always verify your chosen ticker has consistent, accurate volume information and adequate price history before applying this indicator.
DeeptestDeeptest: Quantitative Backtesting Library for Pine Script
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ OVERVIEW
Deeptest is a Pine Script library that provides quantitative analysis tools for strategy backtesting. It calculates over 100 statistical metrics including risk-adjusted return ratios (Sharpe, Sortino, Calmar), drawdown analysis, Value at Risk (VaR), Conditional VaR, and performs Monte Carlo simulation and Walk-Forward Analysis.
█ WHY THIS LIBRARY MATTERS
Pine Script is a simple yet effective coding language for algorithmic and quantitative trading. Its accessibility enables traders to quickly prototype and test ideas directly within TradingView. However, the built-in strategy tester provides only basic metrics (net profit, win rate, drawdown), which is often insufficient for serious strategy evaluation.
Due to this limitation, many traders migrate to alternative backtesting platforms that offer comprehensive analytics. These platforms require other language programming knowledge, environment setup, and significant time investment—often just to test a simple trading idea.
Deeptest bridges this gap by bringing institutional-level quantitative analytics directly to Pine Script. Traders can now perform sophisticated analysis without leaving TradingView or learning complex external platforms. All calculations are derived from strategy.closedtrades.* , ensuring compatibility with any existing Pine Script strategy.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ ORIGINALITY AND USEFULNESS
This library is original work that adds value to the TradingView community in the following ways:
1. Comprehensive Metric Suite: Implements 112+ statistical calculations in a single library, including advanced metrics not available in TradingView's built-in tester (p-value, Z-score, Skewness, Kurtosis, Risk of Ruin).
2. Monte Carlo Simulation: Implements trade-sequence randomization to stress-test strategy robustness by simulating 1000+ alternative equity curves.
3. Walk-Forward Analysis: Divides historical data into rolling in-sample and out-of-sample windows to detect overfitting by comparing training vs. testing performance.
4. Rolling Window Statistics: Calculates time-varying Sharpe, Sortino, and Expectancy to analyze metric consistency throughout the backtest period.
5. Interactive Table Display: Renders professional-grade tables with color-coded thresholds, tooltips explaining each metric, and period analysis cards for drawdowns/trades.
6. Benchmark Comparison: Automatically fetches S&P 500 data to calculate Alpha, Beta, and R-squared, enabling objective assessment of strategy skill vs. passive investing.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ KEY FEATURES
Performance Metrics
Net Profit, CAGR, Monthly Return, Expectancy
Profit Factor, Payoff Ratio, Sample Size
Compounding Effect Analysis
Risk Metrics
Sharpe Ratio, Sortino Ratio, Calmar Ratio (MAR)
Martin Ratio, Ulcer Index
Max Drawdown, Average Drawdown, Drawdown Duration
Risk of Ruin, R-squared (equity curve linearity)
Statistical Distribution
Value at Risk (VaR 95%), Conditional VaR
Skewness (return asymmetry)
Kurtosis (tail fatness)
Z-Score, p-value (statistical significance testing)
Trade Analysis
Win Rate, Breakeven Rate, Loss Rate
Average Trade Duration, Time in Market
Consecutive Win/Loss Streaks with Expected values
Top/Worst Trades with R-multiple tracking
Advanced Analytics
Monte Carlo Simulation (1000+ iterations)
Walk-Forward Analysis (rolling windows)
Rolling Statistics (time-varying metrics)
Out-of-Sample Testing
Benchmark Comparison
Alpha (excess return vs. benchmark)
Beta (systematic risk correlation)
Buy & Hold comparison
R-squared vs. benchmark
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK START
Basic Usage
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as *
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ METRIC EXPLANATIONS
The Deeptest table displays 23 metrics across the main row, with 23 additional metrics in the complementary row. Each metric includes detailed tooltips accessible by hovering over the value.
Main Row — Performance Metrics (Columns 0-6)
Net Profit — (Final Equity - Initial Capital) / Initial Capital × 100
— >20%: Excellent, >0%: Profitable, <0%: Loss
— Total return percentage over entire backtest period
Payoff Ratio — Average Win / Average Loss
— >1.5: Excellent, >1.0: Good, <1.0: Losses exceed wins
— Average winning trade size relative to average losing trade. Breakeven win rate = 100% / (1 + Payoff)
Sample Size — Count of closed trades
— >=30: Statistically valid, <30: Insufficient data
— Number of completed trades. Includes 95% confidence interval for win rate in tooltip
Profit Factor — Gross Profit / Gross Loss
— >=1.5: Excellent, >1.0: Profitable, <1.0: Losing
— Ratio of total winnings to total losses. Uses absolute values unlike payoff ratio
CAGR — (Final / Initial)^(365.25 / Days) - 1
— >=10%: Excellent, >0%: Positive growth
— Compound Annual Growth Rate - annualized return accounting for compounding
Expectancy — Sum of all returns / Trade count
— >0.20%: Excellent, >0%: Positive edge
— Average return per trade as percentage. Positive expectancy indicates profitable edge
Monthly Return — Net Profit / (Months in test)
— >0%: Profitable month average
— Average monthly return. Geometric monthly also shown in tooltip
Main Row — Trade Statistics (Columns 7-14)
Avg Duration — Average time in position per trade
— Mean holding period from entry to exit. Influenced by timeframe and trading style
Max CW — Longest consecutive winning streak
— Maximum consecutive wins. Expected value = ln(trades) / ln(1/winRate)
Max CL — Longest consecutive losing streak
— Maximum consecutive losses. Important for psychological risk tolerance
Win Rate — Wins / Total Trades
— Higher is better
— Percentage of profitable trades. Breakeven win rate shown in tooltip
BE Rate — Breakeven Trades / Total Trades
— Lower is better
— Percentage of trades that broke even (neither profit nor loss)
Loss Rate — Losses / Total Trades
— Lower is better
— Percentage of unprofitable trades. Together with win rate and BE rate, sums to 100%
Frequency — Trades per month
— Trading activity level. Displays intelligently (e.g., "12/mo", "1.5/wk", "3/day")
Exposure — Time in market / Total time × 100
— Lower = less risk
— Percentage of time the strategy had open positions
Main Row — Risk Metrics (Columns 15-22)
Sharpe Ratio — (Return - Rf) / StdDev × sqrt(Periods)
— >=3: Excellent, >=2: Good, >=1: Fair, <1: Poor
— Measures risk-adjusted return using total volatility. Annualized using sqrt(252) for daily
Sortino Ratio — (Return - Rf) / DownsideDev × sqrt(Periods)
— >=2: Excellent, >=1: Good, <1: Needs improvement
— Similar to Sharpe but only penalizes downside volatility. Can be higher than Sharpe
Max DD — (Peak - Trough) / Peak × 100
— <5%: Excellent, 5-15%: Moderate, 15-30%: High, >30%: Severe
— Largest peak-to-trough decline in equity. Critical for risk tolerance and position sizing
RoR — Risk of Ruin probability
— <1%: Excellent, 1-5%: Acceptable, 5-10%: Elevated, >10%: Dangerous
— Probability of losing entire trading account based on win rate and payoff ratio
R² — R-squared of equity curve vs. time
— >=0.95: Excellent, 0.90-0.95: Good, 0.80-0.90: Moderate, <0.80: Erratic
— Coefficient of determination measuring linearity of equity growth
MAR — CAGR / |Max Drawdown|
— Higher is better, negative = bad
— Calmar Ratio. Reward relative to worst-case loss. Negative if max DD exceeds CAGR
CVaR — Average of returns below VaR threshold
— Lower absolute is better
— Conditional Value at Risk (Expected Shortfall). Average loss in worst 5% of outcomes
p-value — Binomial test probability
— <0.05: Significant, 0.05-0.10: Marginal, >0.10: Likely random
— Probability that observed results are due to chance. Low p-value means statistically significant edge
Complementary Row — Extended Metrics
Compounding — (Compounded Return / Total Return) × 100
— Percentage of total profit attributable to compounding (position sizing)
Avg Win — Sum of wins / Win count
— Average profitable trade return in percentage
Avg Trade — Sum of all returns / Total trades
— Same as Expectancy (Column 5). Displayed here for convenience
Avg Loss — Sum of losses / Loss count
— Average unprofitable trade return in percentage (negative value)
Martin Ratio — CAGR / Ulcer Index
— Similar to Calmar but uses Ulcer Index instead of Max DD
Rolling Expectancy — Mean of rolling window expectancies
— Average expectancy calculated across rolling windows. Shows consistency of edge
Avg W Dur — Avg duration of winning trades
— Average time from entry to exit for winning trades only
Max Eq — Highest equity value reached
— Peak equity achieved during backtest
Min Eq — Lowest equity value reached
— Trough equity point. Important for understanding worst-case absolute loss
Buy & Hold — (Close_last / Close_first - 1) × 100
— >0%: Passive profit
— Return of simply buying and holding the asset from backtest start to end
Alpha — Strategy CAGR - Benchmark CAGR
— >0: Has skill (beats benchmark)
— Excess return above passive benchmark. Positive alpha indicates genuine value-added skill
Beta — Covariance(Strategy, Benchmark) / Variance(Benchmark)
— <1: Less volatile than market, >1: More volatile
— Systematic risk correlation with benchmark
Avg L Dur — Avg duration of losing trades
— Average time from entry to exit for losing trades only
Rolling Sharpe/Sortino — Dynamic based on win rate
— >2: Good consistency
— Rolling metric across sliding windows. Shows Sharpe if win rate >50%, Sortino if <=50%
Curr DD — Current drawdown from peak
— Lower is better
— Present drawdown percentage. Zero means at new equity high
DAR — CAGR adjusted for target DD
— Higher is better
— Drawdown-Adjusted Return. DAR^5 = CAGR if max DD = 5%
Kurtosis — Fourth moment / StdDev^4 - 3
— ~0: Normal, >0: Fat tails, <0: Thin tails
— Measures "tailedness" of return distribution (excess kurtosis)
Skewness — Third moment / StdDev^3
— >0: Positive skew (big wins), <0: Negative skew (big losses)
— Return distribution asymmetry
VaR — 5th percentile of returns
— Lower absolute is better
— Value at Risk at 95% confidence. Maximum expected loss in worst 5% of outcomes
Ulcer — sqrt(mean(drawdown^2))
— Lower is better
— Ulcer Index - root mean square of drawdowns. Penalizes both depth AND duration
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ MONTE CARLO SIMULATION
Purpose
Monte Carlo simulation tests strategy robustness by randomizing the order of trades while keeping trade returns unchanged. This simulates alternative equity curves to assess outcome variability.
Method
Extract all historical trade returns
Randomly shuffle the sequence (1000+ iterations)
Calculate cumulative equity for each shuffle
Build distribution of final outcomes
Output
The stress test table shows:
Median Outcome: 50th percentile result
5th Percentile: Worst 5% of outcomes
95th Percentile: Best 95% of outcomes
Success Rate: Percentage of simulations that were profitable
Interpretation
If 95% of simulations are profitable: Strategy is robust
If median is far from actual result: High variance/unreliability
If 5th percentile shows large loss: High tail risk
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ WALK-FORWARD ANALYSIS
Purpose
Walk-Forward Analysis (WFA) is the gold standard for detecting strategy overfitting. It simulates real-world trading by dividing historical data into rolling "training" (in-sample) and "validation" (out-of-sample) periods. A strategy that performs well on unseen data is more likely to succeed in live trading.
Method
The implementation uses a non-overlapping window approach following AmiBroker's gold standard methodology:
Segment Calculation: Total trades divided into N windows (default: 12), IS = ~75%, OOS = ~25%, Step = OOS length
Window Structure: Each window has IS (training) followed by OOS (validation). Each OOS becomes the next window's IS (rolling forward)
Metrics Calculated: CAGR, Sharpe, Sortino, MaxDD, Win Rate, Expectancy, Profit Factor, Payoff
Aggregation: IS metrics averaged across all IS periods, OOS metrics averaged across all OOS periods
Output
IS CAGR: In-sample annualized return
OOS CAGR: Out-of-sample annualized return ( THE key metric )
IS/OOS Sharpe: In/out-of-sample risk-adjusted return
Success Rate: % of OOS windows that were profitable
Interpretation
Robust: IS/OOS CAGR gap <20%, OOS Success Rate >80%
Some Overfitting: CAGR gap 20-50%, Success Rate 50-80%
Severe Overfitting: CAGR gap >50%, Success Rate <50%
Key Principles:
OOS is what matters — Only OOS predicts live performance
Consistency > Magnitude — 10% IS / 9% OOS beats 30% IS / 5% OOS
Window count — More windows = more reliable validation
Non-overlapping OOS — Prevents data leakage
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ TABLE DISPLAY
Main Table — Organized into three sections:
Performance Metrics (Cols 0-6): Net Profit, Payoff, Sample Size, Profit Factor, CAGR, Expectancy, Monthly
Trade Statistics (Cols 7-14): Avg Duration, Max CW, Max CL, Win, BE, Loss, Frequency, Exposure
Risk Metrics (Cols 15-22): Sharpe, Sortino, Max DD, RoR, R², MAR, CVaR, p-value
Color Coding
🟢 Green: Excellent performance
🟠 Orange: Acceptable performance
⚪ Gray: Neutral / Fair
🔴 Red: Poor performance
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ IMPLEMENTATION NOTES
Data Source: All metrics calculated from strategy.closedtrades , ensuring compatibility with any Pine Script strategy
Calculation Timing: All calculations occur on barstate.islastconfirmedhistory to optimize performance
Limitations: Requires at least 1 closed trade for basic metrics, 30+ trades for reliable statistical analysis
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ QUICK NOTES
➙ This library has been developed and refined over two years of real-world strategy testing. Every calculation has been validated against industry-standard quantitative finance references.
➙ The entire codebase is thoroughly documented inline. If you are curious about how a metric is calculated or want to understand the implementation details, dive into the source code -- it is written to be read and learned from.
➙ This description focuses on usage and concepts rather than exhaustively listing every exported type and function. The library source code is thoroughly documented inline -- explore it to understand implementation details and internal logic.
➙ All calculations execute on barstate.islastconfirmedhistory to minimize runtime overhead. The library is designed for efficiency without sacrificing accuracy.
➙ Beyond analysis, this library serves as a learning resource. Study the source code to understand quantitative finance concepts, Pine Script advanced techniques, and proper statistical methodology.
➙ Metrics are their own not binary good/bad indicators. A high Sharpe ratio with low sample size is misleading. A deep drawdown during a market crash may be acceptable. Study each function and metric individually -- evaluate your strategy contextually, not by threshold alone.
➙ All strategies face alpha decay over time. Instead of over-optimizing a single strategy on one timeframe and market, build a diversified portfolio across multiple markets and timeframes. Deeptest helps you validate each component so you can combine robust strategies into a trading portfolio.
➙ Screenshots shown in the documentation are solely for visual representation to demonstrate how the tables and metrics will be displayed. Please do not compare your strategy's performance with the metrics shown in these screenshots -- they are illustrative examples only, not performance targets or benchmarks.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ HOW-TO
Using Deeptest is intentionally straightforward. Just import the library and call DT.runDeeptest() at the end of your strategy code in main scope. .
//@version=6
strategy("My Strategy", overlay=true)
// Import the library
import Fractalyst/Deeptest/1 as DT
// Your strategy logic
fastMA = ta.sma(close, 10)
slowMA = ta.sma(close, 30)
if ta.crossover(fastMA, slowMA)
strategy.entry("Long", strategy.long)
if ta.crossunder(fastMA, slowMA)
strategy.close("Long")
// Run the analysis
DT.runDeeptest()
And yes... it's compatible with any TradingView Strategy! 🪄
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ CREDITS
Author: @Fractalyst
Font Library: by @fikira - @kaigouthro - @Duyck
Community: Inspired by the @PineCoders community initiative, encouraging developers to contribute open-source libraries and continuously enhance the Pine Script ecosystem for all traders.
if you find Deeptest valuable in your trading journey, feel free to use it in your strategies and give a shoutout to @Fractalyst -- Your recognition directly supports ongoing development and open-source contributions to Pine Script.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
█ DISCLAIMER
This library is provided for educational and research purposes. Past performance does not guarantee future results. Always test thoroughly and use proper risk management. The author is not responsible for any trading losses incurred through the use of this code.
BUYSELL WIN [Label Edition]Fibonacci Levels, Code Names, Usage Strategies, Colors
78.6% (fib_786_buy) 💰 Buy Trap (78.6%) A very important entry point (Buy Trap). Considered the deepest level of the consolidation before the uptrend continues. Blue
61.8% (fib_618_buy) 💰 Buy Trap (61.8%) The most common entry point (Buy Trap). When the price consolidates in an uptrend: Green
50.0% 50.00% Mid-trend consolidation level. Yellow
127.2% (fib_1272_sell) 🎯 127.2% target (sell trap) Profit target (Target/Sell Trap) for uptrend trading after the price breaks through the previous High. Orange
161.8% (fib_1618_sell) 🎯 161.8% target (sell trap) Profit target (Target/Sell Trap) The most important and popular for Fibonacci extensions. Red
I created this indicator to help traders who know nothing about trading. It might be worthless if you don't use it. Only 200 baht for this amazing indicator.
VMDivergences◈ DIVERGENCE DETECTION SYSTEM ◈
════════════════════════════════════════════════════════════
▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
█ 🎯 OVERVIEW █
▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄
VMDiv is a professional-grade divergence detection system built on a unique
hybrid oscillator that combines the best of momentum analysis and mean-reversion
theory. Unlike standard divergence indicators that rely on RSI or MACD, this
system uses a custom Volume Momentum oscillator with adjustable characteristics.
═══════════════════════════════════════════════════════════
🔧 THE VM OSCILLATOR ENGINE
═════════════════════════════════════════════════════════════
The core innovation is a hybrid oscillator combining TWO analytical approaches:
┌──────────────────────────────────────────────────────┐
│ COMPONENT 1: EMA MOMENTUM │
│ ════════════════════════ │
│ • Fast EMA minus Slow EMA (similar to MACD) │
│ • Normalized by standard deviation for consistency │
│ • Captures trend strength and directional momentum │
├─────────────────────────────────────────────────────────┤
│ COMPONENT 2: BOLLINGER BAND DISTANCE │
│ ════════════════════════════════════ │
│ • Price distance from Bollinger Band midline │
│ • Normalized to show position within bands (-1 to +1 typically) │
│ • Captures overextension and mean-reversion potential │
├─────────────────────────────────────────────────────────┤
│ THE BLEND │
│ ════════════ │
│ • "Momentum Blend" parameter controls the mix │
│ • 1.0 = Pure momentum oscillator │
│ • 0.0 = Pure mean-reversion oscillator │
│ • 0.5 = Balanced hybrid (often optimal) │
└───────────────────────────────────────────────────┘
═══════════════════════════════════════════════════════
📊 DIVERGENCE TYPES DETECTED
══════════════════════════════════════════════════════
This indicator detects SIX types of divergence patterns:
┌───────────────────────────────────────────────────────┐
│ 🔴 REGULAR BEARISH DIVERGENCE │
│ ══════════════════════════════ │
│ Price: Makes HIGHER HIGH ↗ │
│ Oscillator: Makes LOWER HIGH ↘ │
│ │
│ Interpretation: Momentum is weakening despite higher prices. │
│ Signal: Potential reversal to the DOWNSIDE │
│ Reliability: HIGH - Classic reversal signal at tops │
├────────────────────────────────────────────────────────┤
│ 🟢 REGULAR BULLISH DIVERGENCE │
│ ══════════════════════════════ │
│ Price: Makes LOWER LOW ↘ │
│ Oscillator: Makes HIGHER LOW ↗ │
│ │
│ Interpretation: Momentum is strengthening despite lower prices. │
│ Signal: Potential reversal to the UPSIDE │
│ Reliability: HIGH - Classic reversal signal at bottoms │
├──────────────────────────────────────────────────┤
│ 🟠 HIDDEN BEARISH DIVERGENCE │
│ ════════════════════════════ │
│ Price: Makes LOWER HIGH ↘ │
│ Oscillator: Makes HIGHER HIGH ↗ │
│ │
│ Interpretation: Downtrend showing internal strength. │
│ Signal: Trend CONTINUATION - expect further downside │
│ Best used: During confirmed downtrends │
├──────────────────────────────────────────────────────┤
│ 🟡 HIDDEN BULLISH DIVERGENCE │
│ ════════════════════════════ │
│ Price: Makes HIGHER LOW ↗ │
│ Oscillator: Makes LOWER LOW ↘ │
│ │
│ Interpretation: Uptrend showing internal strength. │
│ Signal: Trend CONTINUATION - expect further upside │
│ Best used: During confirmed uptrends │
├───────────────────────────────────────────────────┤
│ 🟣 DOUBLE TOP DIVERGENCE │
│ ═════════════════════════ │
│ Price: Two SIMILAR HIGHS (within ATR tolerance) │
│ Oscillator: Second high LOWER than first │
│ │
│ Interpretation: Resistance tested twice with weakening momentum. │
│ Signal: Strong reversal setup - HIGH PROBABILITY bearish │
│ Best used: At major resistance levels │
├───────────────────────────────────────────────────────────┤
│ 🔵 DOUBLE BOTTOM DIVERGENCE │
│ ═══════════════════════════ │
│ Price: Two SIMILAR LOWS (within ATR tolerance) │
│ Oscillator: Second low HIGHER than first │
│ │
│ Interpretation: Support tested twice with strengthening momentum. │
│ Signal: Strong reversal setup - HIGH PROBABILITY bullish │
│ Best used: At major support levels │
└──────────────────────────────────────────────────┘
Cosmic Volume Analyzer [JOAT]
Cosmic Volume Analyzer - Astrophysics Edition
Overview
Cosmic Volume Analyzer is an open-source oscillator indicator that applies astrophysics-inspired concepts to volume analysis. It classifies volume into buy/sell categories, calculates volume flow, detects accumulation/distribution phases, identifies climax volume events, and uses gravitational and stellar mass analogies to visualize volume dynamics.
What This Indicator Does
The indicator calculates and displays:
Volume Classification - Categorizes each bar as CLIMAX_BUY, CLIMAX_SELL, HIGH_BUY, HIGH_SELL, NORMAL_BUY, or NORMAL_SELL
Volume Flow - Percentage showing buy vs sell pressure over a lookback period
Buy/Sell Volume - Separated volume based on candle direction
Accumulation/Distribution - Phase detection using Money Flow Multiplier
Volume Oscillator - Fast vs slow volume EMA comparison
Gravitational Pull - Volume-weighted price attraction metric
Stellar Mass Index - Volume ratio combined with price momentum
Black Hole Detection - Identifies extremely low volume periods (liquidity voids)
Supernova Events - Detects extreme volume with extreme price movement
Orbital Cycles - Sine-wave based cyclical visualization
How It Works
Volume classification uses volume ratio and candle direction:
classifyVolume(series float vol, series float close, series float open) =>
float avgVol = ta.sma(vol, 20)
float volRatio = avgVol > 0 ? vol / avgVol : 1.0
if volRatio > 1.5
if close > open
classification := "CLIMAX_BUY"
else
classification := "CLIMAX_SELL"
else if volRatio > 1.2
// HIGH_BUY or HIGH_SELL
else
// NORMAL_BUY or NORMAL_SELL
Volume flow separates buy and sell volume over a period:
calculateVolumeFlow(series float vol, series float close, simple int period) =>
float currentBuyVol = close > open ? vol : 0.0
float currentSellVol = close < open ? vol : 0.0
// Accumulate in buffers
float flow = (buyVolume - sellVolume) / totalVol * 100
Accumulation/Distribution uses the Money Flow Multiplier:
float mfm = ((close - low) - (high - close)) / (high - low)
float mfv = mfm * vol
float adLine = ta.cum(mfv)
if adLine > adEMA and ta.rising(adLine, 3)
phase := "ACCUMULATION"
else if adLine < adEMA and ta.falling(adLine, 3)
phase := "DISTRIBUTION"
Gravitational pull uses volume-weighted price distance:
gravitationalPull(series float vol, series float price, simple int period) =>
float massCenter = ta.vwma(price, period)
float distance = math.abs(price - massCenter)
float mass = vol / ta.sma(vol, period)
float gravity = distance > 0 ? mass / (distance * distance) : 0.0
Signal Generation
Signals are generated based on volume conditions:
Buy Climax: Volume exceeds 2 standard deviations above average on bullish candle
Sell Climax: Volume exceeds 2 standard deviations above average on bearish candle
Strong Buy Flow: Volume flow exceeds positive threshold (default 45%)
Strong Sell Flow: Volume flow exceeds negative threshold (default -45%)
Supernova: Volume 3x average AND price change 3x average
Black Hole: Volume 2 standard deviations below average
Dashboard Panel (Top-Right)
Volume Class - Current volume classification
Volume Flow - Buy/sell flow percentage
Buy Volume - Accumulated buy volume
Sell Volume - Accumulated sell volume
A/D Phase - ACCUMULATION/DISTRIBUTION/NEUTRAL
Volume Strength - Normalized volume strength
Gravity Pull - Current gravitational metric
Stellar Mass - Current stellar mass index
Cosmic Field - Combined cosmic field strength
Black Hole - Detection status and void strength
Signal - Current actionable status
Visual Elements
Volume Ratio Columns - Colored bars showing normalized volume
Volume Flow Line - Main oscillator showing flow direction
Flow EMA - Smoothed flow for trend reference
Volume Oscillator - Area plot showing fast/slow comparison
Gravity Field - Area plot showing gravitational pull
Orbital Cycle - Circle plots showing cyclical pattern
Stellar Mass Line - Line showing mass index
Climax Markers - Fire emoji for buy climax, snowflake for sell climax
Supernova Markers - Diamond shapes for extreme events
Black Hole Markers - X-cross for liquidity voids
A/D Phase Background - Subtle background color based on phase
Input Parameters
Volume Period (default: 20) - Period for volume calculations
Distribution Levels (default: 5) - Granularity of distribution analysis
Flow Threshold (default: 1.5) - Multiplier for flow significance
Accumulation Period (default: 14) - Period for A/D calculation
Gravitational Analysis (default: true) - Enable gravity metrics
Black Hole Detection (default: true) - Enable void detection
Stellar Mass Calculation (default: true) - Enable mass index
Orbital Cycles (default: true) - Enable cyclical visualization
Supernova Detection (default: true) - Enable extreme event detection
Suggested Use Cases
Identify accumulation phases for potential long entries
Watch for distribution phases as potential exit signals
Use climax volume as potential exhaustion indicators
Monitor volume flow for directional bias
Avoid trading during black hole (low liquidity) periods
Watch for supernova events as potential trend acceleration
Timeframe Recommendations
Best on 15m to Daily charts. Volume analysis requires sufficient trading activity for meaningful readings.
Limitations
Volume data quality varies by exchange and instrument
Buy/sell separation is based on candle direction, not actual order flow
Astrophysics concepts are analogies, not literal physics
A/D phase detection may lag during rapid transitions
Open-Source and Disclaimer
This script is published as open-source under the Mozilla Public License 2.0 for educational purposes. It does not constitute financial advice. Past performance does not guarantee future results. Always use proper risk management.
- Made with passion by officialjackofalltrades
Adaptive Trend Envelope [BackQuant]Adaptive Trend Envelope
Overview
Adaptive Trend Envelope is a volatility-aware trend-following overlay designed to stay responsive in fast markets while remaining stable during slower conditions. It builds a dynamic trend spine from two exponential moving averages and surrounds it with an adaptive envelope whose width expands and contracts based on realized return volatility. The result is a clean, self-adjusting trend structure that reacts to market conditions instead of relying on fixed parameters.
This indicator is built to answer three core questions directly on the chart:
Is the market trending or neutral?
If trending, in which direction is the dominant pressure?
Where is the dynamic trend boundary that price should respect?
Core trend spine
At the heart of the indicator is a blended trend spine:
A fast EMA captures short-term responsiveness.
A slow EMA captures structural direction.
A volatility-based blend weight dynamically shifts influence between the two.
When short-term volatility is low relative to long-term volatility, the fast EMA has more influence, keeping the trend responsive. When volatility rises, the blend shifts toward the slow EMA, reducing noise and preventing overreaction. This blended output is then smoothed again to form the final trend spine, which acts as the structural backbone of the system.
Volatility-adaptive envelope
The envelope surrounding the trend spine is not based on ATR or fixed percentages. Instead, it is derived from:
Log returns of price.
An exponentially weighted variance estimate.
A configurable multiplier that scales envelope width.
This creates bands that automatically widen during volatile expansions and tighten during compression. The envelope therefore reflects the true statistical behavior of price rather than an arbitrary distance.
Inner hysteresis band
Inside the main envelope, an inner band is constructed using a hysteresis fraction. This inner zone is used to stabilize regime transitions:
It prevents rapid flipping between bullish and bearish states.
It allows trends to persist unless price meaningfully invalidates them.
It reduces whipsaws in sideways conditions.
Trend regime logic
The indicator operates with three regime states:
Bullish
Bearish
Neutral
Regime changes are confirmed using a configurable number of bars outside the adaptive envelope:
A bullish regime is confirmed when price closes above the upper envelope for the required number of bars.
A bearish regime is confirmed when price closes below the lower envelope for the required number of bars.
A trend exits back to neutral when price reverts through the trend spine.
This structure ensures that trends are confirmed by sustained pressure rather than single-bar spikes.
Active trend line
Once a regime is active, the indicator plots a single dominant trend line:
In a bullish regime, the lower envelope becomes the active trend support.
In a bearish regime, the upper envelope becomes the active trend resistance.
In neutral conditions, price itself is used as a placeholder.
This creates a simple, actionable visual reference for trend-following decisions.
Directional energy visualization
The indicator uses layered fills to visualize directional pressure:
Bullish energy fills appear when price holds above the active trend line.
Bearish energy fills appear when price holds below the active trend line.
Opacity gradients communicate strength and persistence rather than binary states.
A subtle “rim” effect is added using ATR-based offsets to give depth and reinforce the active side of the trend without cluttering the chart.
Signals and trend starts
Discrete signals are generated only when a new trend regime begins:
Buy signals appear at the first confirmed transition into a bullish regime.
Sell signals appear at the first confirmed transition into a bearish regime.
Signals are intentionally sparse. They are designed to mark regime shifts, not every pullback or continuation, making them suitable for higher-quality trend entries rather than frequent trading.
Candle coloring
Optional candle coloring reinforces regime context:
Bullish regimes tint candles toward the bullish color.
Bearish regimes tint candles toward the bearish color.
Neutral states remain visually muted.
This allows the chart to communicate trend state even when the envelope itself is partially hidden or de-emphasized.
Alerts
Built-in alerts are provided for key trend events:
Bull trend start.
Bear trend start.
Transition from trend to neutral.
Price crossing the trend spine.
These alerts support hands-off trend monitoring across multiple instruments and timeframes.
How to use it for trend following
Trend identification
Only trade in the direction of the active regime.
Ignore counter-trend signals during confirmed trends.
Entry alignment
Use the first regime signal as a structural entry.
Use pullbacks toward the active trend line as continuation opportunities.
Trend management
As long as price respects the active envelope boundary, the trend remains valid.
A move back through the spine signals loss of trend structure.
Market filtering
Periods where the indicator remains neutral highlight non-trending environments.
This helps avoid forcing trades during chop or compression.
Adaptive Trend Envelope is designed to behave like a living trend structure. Instead of forcing price into static rules, it adapts to volatility, confirms direction through sustained pressure, and presents trend information in a clean, readable form that supports disciplined trend-following workflows.
Spot Futures Divergence & Auction ContextSpot–Futures Divergence & Auction Context
Spot–Futures Divergence & Auction Context is a contextual market analysis indicator designed to help traders understand where the market is positioned and when structural divergence is meaningful.
This tool compares spot and futures price structure using confirmed swing pivots and overlays that information with VWAP location, auction regime, and higher-timeframe (HTF) trend context.
⚠️ This indicator is NOT a buy/sell signal generator.
It is intended for discretionary decision support and market context only.
🔍 What This Indicator Shows
1️⃣ Spot–Futures Structural Divergence
Identifies divergence between spot and futures swing structure
Highlights where derivatives are leading or lagging cash markets
Uses confirmed pivots only (non-repainting)
2️⃣ Divergence Quality (DIV-A / DIV-B)
DIV-A: Divergence aligned with HTF trend
DIV-B: Divergence against or without HTF alignment
Helps distinguish high-quality context from early warnings
3️⃣ VWAP Context & Deviation Bands
Session VWAP plotted on futures
Optional VWAP deviation bands (±1σ / ±2σ / ±3σ) for auction stretch context
Bands are visual only, not signals
4️⃣ Auction Regime Detection
Classifies market as BALANCED or IMBALANCED
Helps avoid divergence during strong trend / directional auctions
5️⃣ Options Bias Panel (Context Only)
Provides a high-level directional or volatility bias, such as:
CALL BIAS
PUT BIAS
SELL PREMIUM
WAIT
This bias is informational, not an instruction to trade.
⚙️ Key Settings Explained
Futures / Execution Symbol
Select the futures or derivative symbol you are trading (e.g., NIFTY1!, BANKNIFTY1!, ES1!, BTCUSDT.P).
Spot / Cash Reference Symbol
Select the corresponding spot or cash index used for structural comparison.
Divergence Display Mode
Show All → Displays all divergences
Hide in Imbalanced → Suppresses divergences during strong directional auctions
DIV-A only in Imbalanced → Shows only HTF-aligned divergences on trend days
This is a discipline and visibility control, not a signal filter.
VWAP Deviation Bands
Optional visual bands to assess how far price is trading from fair value.
Best used for context, not entries.
🧭 How to Use (1-Page User Guide)
Recommended Workflow
Start with auction regime
Balanced → mean-reversion context
Imbalanced → trend / momentum context
Observe VWAP location
Near VWAP → fair value
Extended → stretched auction
Note Spot–Futures divergence
DIV-A → higher contextual importance
DIV-B → early warning or risk signal
Use Options Bias panel
As a guideline, not a trigger
Especially useful for options and volatility strategies
🚫 When to Ignore Divergence
Strong imbalanced trend with steep VWAP slope
News-driven or event-driven sessions
Very early session before structure forms
⚠️ Important Disclaimers
This indicator does not generate buy/sell signals.
No profitability or performance claims are made.
Past behavior does not guarantee future results.
Trading futures, options, and leveraged products involves significant risk.
Use this tool for analysis and education only.
📊 Best Use Cases
Index futures & options
Spot vs derivative structure analysis
Intraday auction and VWAP-based context
Risk awareness and trade selection support
[turpsy]MOR-Fractal-Opening RangeThis script combines the Midnight Opening Range and the Fractal identification that I have published individually before. The original authors have been credited too.
The combination helps to reduce multiple indicators on your chart. Also, you can enable or disable the MOR.
Moreso, with the previous separate indicators, the current opening range and historical opening range do not show on 4hr timeframe, in this combined one, I have fixed that. the current opening range shows up to daily and weekly timeframe.
It also shows the 1st presented fair value gap, pivot points are also identified based on the session.
Supertrend BUY Only - Optimized for Gold M15 TimeframeOverview
The Supertrend BUY Only - Production Optimized is a high-performance trend-following indicator specifically tuned for XAUUSD (Gold) on the 15-minute timeframe. Unlike standard Supertrend scripts, this version focuses exclusively on bullish cycles to align with long-term upward bias and uses parameters discovered through deep data analysis of over 20,000 bars of historical market data.
Key Features
Data-Optimized Parameters: Defaults are set to ATR Period 7 and Multiplier 2.1, which backtesting has shown to provide a superior balance between sensitivity and noise reduction for Gold.
Production-Ready Alerts: Includes built-in alertcondition triggers for both BUY (Trend Flip) and STOP BUY (Trend Exit), complete with dynamic messages that include price and interval.
Trailing Support Band: Uses a trailing logic that locks in support levels during upward moves, preventing the band from dropping until the trend officially reverses.
Clean Visuals: Focuses on chart clarity by only plotting the support line during active uptrends and utilizing clean shape labels for entries and exits.
How to Use
Entry (BUY): When the Supertrend line flips from Red to Green and a "BUY" label appears. This indicates bullish momentum has overcome recent volatility.
Exit (STOP BUY): When the price closes below the Green support line. The indicator will plot a red "X" and clear the green background.
Setting Alerts: * Click the Alerts icon in TradingView.
Select this indicator under "Condition."
Choose "BUY Signal" for entries and "STOP BUY / EXIT" for managing your trade or taking profit.
Technical Details
The script allows users to toggle between the TradingView (RMA) ATR calculation and the Standard (SMA) method. For production and live trading, the RMA method is recommended as it provides a smoother response to volatility spikes common in the Gold market.
PKS INDIA RSI + VWAP Multi TF Strategy (Backtest)🔥 Strategy Logic
Indicator दो Timeframes पर Market Strength चेक करता है:
SELL Condition
RSI (1 Hour) < 50
RSI (15 Minute) < 50
Price VWAP के नीचे हो
Price VWAP के पास आए (Pullback)
Bearish Confirmation Candle बने
BUY Condition
RSI (1 Hour) > 50
RSI (15 Minute) > 50
Price VWAP के ऊपर हो
Price VWAP के पास आए (Pullback)
Bullish Confirmation Candle बने
इससे Indicator केवल वही Signals देता है जहाँ Market में Clear Direction + Strong Momentum + Smart Entry Point मिलता है।
🎯 Best Timeframe
✔️ Recommended: 15 Minute Chart
✔️ Works on: Forex, Crypto, Indices, Commodities, Stocks
Stochastic Extreme Oscillator [MatrixQuantLabs]Stochastic Extreme Oscillator is an enhanced stochastic-based oscillator designed to highlight market extremes, momentum shifts, and potential reversal zones with improved visual clarity and signal filtering.
This indicator builds upon the classic Stochastic Oscillator by focusing on extreme zone behavior, peak & trough signals, and optional divergence detection, making it suitable for both discretionary and systematic traders.
Key Features
Extreme Zone Visualization
• Multi-level overbought (80–100) and oversold (0–20) zones with adaptive color intensity help assess the strength and risk level of market extremes at a glance.
Momentum-Aware Coloring
• The %D line dynamically changes color based on its position relative to the zero line, providing an intuitive view of bullish, neutral, and bearish momentum states.
Peak & Trough Signals
• Optional bullish and bearish signals are triggered only when %K / %D cross occurs inside extreme zones, helping filter out low-quality signals in mid-range conditions.
Regular Divergence Detection
• Built-in bullish and bearish divergence detection based on pivot structure, allowing early identification of potential trend reversals.
Clean & Focused Design
• The indicator emphasizes the %D line as the primary signal source, while %K is used internally for logic, keeping the chart uncluttered and easy to read.
Customization
• Adjustable %K / %D lengths and smoothing
• Toggle peak & trough signals on/off
• Optional divergence detection with configurable pivot sensitivity
• Designed to work across different markets and timeframes
Usage Notes
• Best used as a momentum and extreme-condition oscillator, not as a standalone trading system
• Signals are most effective when combined with trend context, price structure, or higher-timeframe analysis
• Divergence signals may appear with delay due to pivot confirmation logic
Disclaimer
This indicator is intended for educational and analytical purposes only and does not constitute financial advice. Always apply proper risk management and confirm signals with additional analysis.
HTF Pivots SignalsIntroduction :
HPS (HTF Pivot Signals) provides traders with a systematic approach to Higher Timeframe structure analysis and signal confirmation. Designed for traders seeking to identify confirmed structure changes, this indicator detects HTF pivot interactions and generates entry signals when price confirms beyond chart timeframe pivot levels. The indicator helps analysts identify key structure breaks, momentum shifts, and high-probability entry points based on confirmed pivot interactions.
Description :
HPS is rooted in the principle that Higher Timeframe structure changes provide context for lower timeframe price action. When an HTF pivot is interacted with (mitigated), it signals a potential opportunity for a mean reversal. The indicator then waits for confirmation on the chart timeframe before generating a signal, ensuring only confirmed setups are highlighted.
Main indicator screenshot showing HTF pivots and confirmation signals
The system operates by detecting pivot highs and lows on a higher timeframe, tracking when these pivots are interacted with, and confirming signals when price closes beyond chart timeframe pivot levels. This two-step process—interaction followed by confirmation—filters out false signals and provides only actionable setups.
HPS automatically calculates the optimal higher timeframe pairing (typically 15-16x the chart timeframe) or allows manual selection. The indicator remains stable and non-repainting, offering traders reliable, unchanged levels within the given time period. Pivot cleanup is managed by mitigation order rather than age, ensuring the most recent interactions remain visible while older ones are removed systematically.
Key Features:
Automatic HTF Selection: The indicator automatically calculates the optimal higher timeframe pairing based on your chart timeframe, typically using 15-16x multiples (e.g., 5m → 1h, 15m → 4h, 1h → 1D). For a more dynamic experience, the Automatic feature autonomously adjusts the higher timeframe pairing based on the current chart timeframe, ensuring accurate alignment with structure analysis. Manual override is available for custom timeframe selection.
Confirmed Pivot Detection: HPS only displays confirmed HTF pivots that have been interacted with. Unlike basic pivot indicators that show all pivots, HPS requires pivot interaction before displaying, eliminating noise and focusing on actionable structure changes. Pivots are marked with PH (Pivot High) and PL (Pivot Low) labels when enabled.
Signal Confirmation System: When an HTF pivot is interacted with, a pending signal is created signaling a potential mean reversal opportunity. The signal confirms when price closes beyond the chart timeframe pivot level—pivot low for bearish signals, pivot high for bullish signals. Confirmed signals display with OB+ (bullish) or OB- (bearish) labels and extending confirmation lines that mark the entry level.
Mitigation-Based Cleanup: Pivot cleanup is managed by mitigation order rather than age. The system maintains the latest mitigated pivots while removing older ones based on interaction time. This ensures recent interactions remain visible while preventing chart clutter. The maximum number of mitigated pivots displayed is configurable based on the max pivots setting.
Customizable Display: Full control over visual elements including pivot highs/lows visibility, pivot labels (PH/PL), confirmation lines, colors, and line width. Confirmation line labels (OB+/OB-) always display regardless of label toggle settings, ensuring signal visibility. Adjust the maximum number of pivots displayed to match your charting style and analysis needs.
Stop Level Calculation: Automatically calculates stop levels based on the maximum price (for bearish signals) or minimum price (for bullish signals) from signal creation to confirmation. These levels represent the risk point for each confirmed signal, providing clear risk management reference points.
Stop level calculation visualization
Multi-Timeframe Compatibility: Works across all TradingView timeframes and market types including Forex, Crypto, Stocks, and Futures. The automatic HTF selection adapts to any chart timeframe, providing consistent structure analysis regardless of the trading instrument or timeframe selected.
Multi-timeframe compatibility example
Usage Guidance :
Add HPS (HTF Pivot Signals) to your TradingView chart.
Select your preferred HTF pairing (Automatic or Manual) and adjust display settings to match your visual preferences.
Monitor for HTF pivot interactions—when price mitigates an HTF pivot, a pending signal is created signaling a potential mean reversal opportunity. Wait for confirmation when price closes beyond the chart timeframe pivot level, indicated by OB+ or OB- labels.
Use the confirmation lines and stop levels to identify entry points and manage risk. Combine with your existing analysis methods to enhance structure-based trading decisions.
Step-by-step usage guide
Terms and Conditions
Our charting tools are products provided for informational and educational purposes only and do not constitute financial, investment, or trading advice. Our charting tools are not designed to predict market movements or provide specific recommendations. Users should be aware that past performance is not indicative of future results and should not be relied upon for making financial decisions. By using our charting tools, the purchaser agrees that the seller and the creator are not responsible for any decisions made based on the information provided by these charting tools. The purchaser assumes full responsibility and liability for any actions taken and the consequences thereof, including any loss of money or investments that may occur as a result of using these products. Hence, by purchasing these charting tools, the customer accepts and acknowledges that the seller and the creator are not liable nor responsible for any unwanted outcome that arises from the development, the sale, or the use of these products. Finally, the purchaser indemnifies the seller from any and all liability. If the purchaser was invited through the Friends and Family Program, they acknowledge that the provided discount code only applies to the first initial purchase. The purchaser is therefore responsible for cancelling – or requesting to cancel – their subscription in the event that they do not wish to continue using the product at full retail price. If the purchaser no longer wishes to use the products, they must unsubscribe from the membership service, if applicable. We hold no reimbursement, refund, or chargeback policy. Once these Terms and Conditions are accepted by the Customer, before purchase, no reimbursements, refunds or chargebacks will be provided under any circumstances.
By continuing to use these charting tools, the user acknowledges and agrees to the Terms and Conditions outlined in this legal disclaimer.
Waves UltimateWaves Ultimate is a comprehensive Elliott Wave analysis tool designed to assist traders in identifying and validating wave structures in real-time. This indicator combines automatic wave detection with strict Elliott Wave rule validation, Fibonacci projections, and visual wave labeling to provide a complete wave analysis suite.
CVD Flow Labels for Sessions Ranges [AMT Edition]CVD Flow Labels for Session Ranges
Description:
This script provides a session-aware Cumulative Volume Delta (CVD) analysis designed to enhance the “Session Ranges ” framework by combining price extremes with detailed volume flow dynamics. Unlike generic trend or scalping indicators, this tool focuses on identifying aggressive buying and selling pressure, distinguishing between absorption (failed auctions where aggressive flows are rejected) and acceptance (confirmed continuation of flows).
How it works:
CVD Calculation: The script calculates delta for each bar using a choice of Total, Periodic, or EMA-based cumulative methods. Delta represents the net difference between estimated buying and selling volume per bar.
Normalization: By normalizing delta relative to recent volatility, it highlights extreme flows that are statistically significant, making large shifts in market sentiment easier to spot.
Session-Specific Analysis: The indicator separates Asia, London, and New York sessions to allow context-sensitive interpretation of price and volume interactions. Each session’s extremes are monitored, and flow labels are plotted relative to these extremes.
Flow Labels: Bullish and bearish absorption (“ABS”) and acceptance (“ACC WEAK/STRONG”) labels provide immediate visual cues about whether aggressive flows are being absorbed or accepted at key price levels.
Alerts: Configurable alerts trigger when absorption or acceptance occurs, supporting active trading or strategy automation.
Originality & Usefulness:
This script is original because it integrates volume-based auction theory with session-specific market structure, rather than simply showing trend or scalping signals. By combining CVD dynamics with session extreme levels from the “Session Ranges ” script, traders can:
Identify where price is likely to be accepted or rejected.
Confirm aggressive buying or selling flows before entering trades.
Time entries near session extremes with higher probability setups.
How to use:
Apply the “Session Ranges ” to see session highs, lows, and interaction lines.
Use this CVD Flow Labels script to visualize absorption and acceptance at these session levels.
Enter trades based on alignment of session extremes and flow signals:
Absorption at a session extreme may indicate a potential reversal.
Acceptance suggests continuation in the direction of the flow.
Alerts can help manage trades without constant screen monitoring.
This tool is designed to give traders a structured, session-based view of market auctions, providing actionable insights that go beyond typical trend-following or scalping methods. It emphasizes flow analysis and statistical extremes, enabling traders to make more informed decisions grounded in market microstructure.
Fair Value Gaps w Signals fair value gaps for resistance and support. It is important to understand ranges with this. An open bearish fair value gaps can indicate a bearish range. A bullish fair value gaps in premium can indicate retracement into the bearish range. A fair value gaps on a high time frame in discount of the range can be a indicator to go long. one can play the fair value gaps in discount or a range back into it for longs. negation of the fair value gaps candle bearish or bullish is stop loss. One would want to see a small time frame turn around story within the fair value gaps you are trading. FVG are support and resistance until the market is balanced. A bearish fair value gaps untouched can indicate the end of a range. The candle before the 1st bullsih fair value gaps could be the beginning of the range. all time frames
Chainbey Ai - HTF Trend Matrix (Clean)Chainbey Ai – HTF Trend Matrix is a professional, higher-timeframe trend detection indicator designed to give traders a clean, reliable market bias, regardless of the chart timeframe they are trading on.
This indicator automatically analyzes multiple higher timeframes (HTFs) and combines:
EMA trend direction
Trend strength (ADX)
Market structure (trend vs range)
Trend disagreement across HTFs
Reversal probability estimation
All results are displayed in a compact table at the bottom-right, making it perfect for scalpers, day traders, and swing traders who need fast, decision-ready information.
🧠 What This Indicator Solves
❌ No more guessing the higher-timeframe trend
❌ No more trading against the main market bias
❌ No more confusion between trend vs range
✅ Clear BULLISH / BEARISH / RANGE bias
✅ Strength score to avoid weak trends
✅ Reversal probability to manage risk
📊 How to Read the Table (User Manual)
🔹 FINAL Row
Example:
FINAL | BEARISH TREND | -46
Text (BEARISH / BULLISH / RANGE) → Overall market bias
Number (-46) → Trend Strength Score
Trend Score Guide:
Score Meaning
0 to ±20 No trend / Choppy
±20 to ±40 Weak trend
±40 to ±70 Healthy trend
±70+ Very strong / extended trend
📌 Negative = Bearish
📌 Positive = Bullish
🔹 REVERSAL – Possibility (%)
Example:
REVERSAL | Possibility | 45%
This shows the chance of trend exhaustion or reversal.
Reversal % Meaning
0–30% Strong trend continuation
30–50% Normal pullback risk
50%+ High reversal probability
70%+ Dangerous to chase trades
📌 Use this to avoid late entries.
🔹 HTF Rows (60 / 240 / D)
Each row shows:
DIR / STRUCT
Direction from EMA trend
Market structure (TREND / RANGE)
ADX
Trend strength
STRONG / MEDIUM / CHOP
📌 If multiple HTFs agree → higher confidence
📌 If HTFs conflict → reduce position size or wait
🛠 Recommended Trading Usage
✅ Best Practices
Trade in the direction of FINAL trend
Enter on pullbacks, not breakouts
Use lower timeframes only for entries
❌ Avoid
Trading against FINAL bias
Chasing trades when reversal % is high
Over-leveraging in CHOP conditions
🎯 Ideal For
Crypto traders (Spot & Futures)
Forex traders
Gold / Commodity traders
Scalping, Intraday & Swing trading
⚠️ Disclaimer
This indicator is a decision-support tool, not financial advice. Always combine it with proper risk management, confirmations, and your trading plan.
ORB W/ Custom time FramesRelease Notes: Simplified ORB (Opening Range Breakout)
This indicator is a streamlined, high-performance tool designed to identify the Opening Range—one of the most widely used concepts by professional floor traders and institutional scalpers. It marks the high, low, and midpoint of the initial balance of the market, providing you with a "map" for the rest of the trading session.
Key Features
Customizable Timeframes: Define your opening range window (e.g., the first 5, 15, or 30 minutes) regardless of what timeframe you are currently viewing.
Custom Session Support: Choose between standard market hours (09:30–16:00) or define your own custom window (e.g., the London Open or the first hour of "Power Hour").
Real-Time Midpoint Calculation: Automatically plots the 50% Equilibrium level between the high and low, serving as a pivot point for intraday bias.
Dynamic Updating: During the ORB window, the lines adjust in real-time as new highs or lows are set. Once the window expires, the levels lock in place to act as support and resistance.
Clean Visuals: Utilizes a lightweight line drawing system that is easy on your GPU and keeps the chart clutter-free.
Why This is Essential for Scalping
Scalpers rely on volatility and clear "lines in the sand." The Opening Range Breakout (ORB) provides exactly that:
The "Opening Drive": If price breaks the ORB High with high volume, scalpers look for quick "long" momentum plays. Conversely, a break below the ORB Low signals a bearish trend.
The Midpoint Pivot: The 50% level (Mid) is often treated as the "Fair Value" of the morning. If price is above the mid, the bias is bullish; if below, the bias is bearish.
Stop Loss / Take Profit Anchor: The ORB High and Low act as natural areas for placing stops or targets. A failed breakout that returns inside the range often targets the opposite side of the box.
GCM Price Volume Trend [Dual Signal Ribbon]1. Title
GCM Price Volume Trend
2. Description (Copy & Paste)
Overview
The GCM Price Volume Trend (PVT) is an advanced enhancement of the classic Price Volume Trend indicator. While standard PVT indicators typically use a single signal line, this version introduces a Dual Signal Ribbon System. This allows traders to visualize trend strength, filter out market noise, and identify momentum shifts more accurately.
This script is built upon the foundational logic of the Price Volume Trend indicator by @everget, upgraded here to Pine Script v6 with significant functional additions.
How It Works
The Price Volume Trend (PVT) is similar to On Balance Volume (OBV), but with a key difference: while OBV adds all volume on an up day, PVT adds only a portion of the volume proportional to the percentage price change. This makes PVT a more accurate representation of money flow relative to price movement.
Key Features in This Version
1. Dual Signal Ribbon: Unlike the original single-line version, this indicator plots two signal lines. The area between them acts as a "Cloud" or "Ribbon."
o Green Ribbon: Indicates strong bullish momentum.
o Red Ribbon: Indicates bearish momentum.
o Narrow/Twisting Ribbon: Indicates consolidation or indecision.
2. 7 Smoothing Algorithms: You are no longer limited to just SMA or EMA. You can independently set both signal lines to use:
o SMA (Simple)
o EMA (Exponential)
o WMA (Weighted)
o RMA (Rolling/Wilder's)
o HMA (Hull - Great for reducing lag)
o VWMA (Volume Weighted)
o LSMA (Least Squares / Linear Regression)
3. Visual Customization: Fully standardized coloring system with adjustable opacity for the ribbons to keep your chart clean.
How to Use
• Trend Following: When the main PVT line is above both signal lines and the ribbon is Green, the trend is Bullish.
• Crossovers: A crossover of the PVT line above the Primary Signal (Signal 1) is an early entry warning. A crossover above the Secondary Signal (Signal 2) confirms the trend.
• Divergence: If Price makes a Higher High but the PVT line makes a Lower High (and fails to break above the ribbon), look for a potential reversal.
Settings
• Signal 1 & 2 Type/Length: Customize the sensitivity of the ribbon.
• Style & Colors: Adjust Bull/Bear colors and transparency levels to fit your dark or light theme.
Credits
• Original PVT script logic inspired by @everget.
• Modifications, Dual-Signal logic, and v6 upgrade by @uniGram.
ACP ProDescription
ACP (Advanced Chart Patterns) detects complex multi-point patterns including Head & Shoulders (both regular and inverse), triangles (symmetrical, ascending, descending), wedges (rising, falling), and channels (ascending, descending, horizontal).
Optimus S/R ZonesEnhanced S/R Zones Pro is a sophisticated Support and Resistance indicator designed for traders who need reliable, validated S/R levels with professional-grade visualization. Unlike basic pivot indicators, this tool validates levels based on historical price interaction and provides comprehensive analysis of your current position within the market structure.
✨ Key Features
📊 Extended Lookback Analysis
Lookback Range: 20-500 bars (far beyond standard 80-bar limits)
Pivot Strength: Adjustable 2-10 bars for confirmation
Separate Controls: Independent max levels for support (1-8) and resistance (1-8)
Smart Filtering: Automatic level spacing with customizable minimum distance (0.3-5%)
🎨 Advanced Zone Visualization
Three Zone Styles:
Filled: Solid colored zones
Outlined: Border-only zones
Both: Combined for maximum visibility
Adjustable Transparency: 50-95% opacity control
Dynamic Extension: Zones extend to the right indefinitely
Custom Zone Width: 0.05-1.0% of price
💪 Level Strength System
Touch Validation: Only shows levels tested multiple times
Minimum Touches: Filter for 1-5 minimum confirmations
Color Intensity: Stronger levels (more touches) display darker/brighter
Touch Detection: Customizable sensitivity (0.1-1.0% range)
Independent Display: Show touch counts without color coding
📱 Enhanced Dashboard
Level Count: Active support/resistance zones
Distance Metrics: Percentage to nearest S/R levels
Range Position: Where price sits between S/R (0-100%)
Color Coding: Visual feedback on market position
Four Positions: Top/Bottom, Left/Right placement
🎭 Customizable Visuals
Label Sizes: Tiny, Small, Normal, Large, Huge
Adjustable Line Width: 1-4 pixels
Custom Colors: Full color picker for support/resistance
Optional Touch Count: Toggle touch numbers on/off
Midpoint Line: Shows equilibrium between nearest S/R
🔔 Smart Alerts
Proximity Alerts: Triggers when approaching support zones
Resistance Alerts: Triggers when nearing resistance zones
Customizable Range: Based on touch detection sensitivity
🔧 How It Works
1. Pivot Detection
The indicator scans historical price action using configurable pivot strength to identify significant highs and lows. Extended lookback allows detection of major structural levels that shorter timeframes might miss.
2. Touch Validation
Each potential level is validated by counting how many times price has tested it within the specified touch detection range. Only levels meeting the minimum touch threshold are displayed.
3. Strength Ranking
Levels are ranked by:
Number of touches (primary)
Proximity to current price (secondary)
This ensures the most reliable and relevant levels are always shown.
4. Smart Filtering
The minimum distance filter prevents level clustering, keeping your chart clean and focusing only on distinct, actionable zones.
💡 Use Cases
Swing Trading
Identify major support/resistance for position entries
Set profit targets at strong resistance levels
Place stops below validated support zones
Day Trading
Quick identification of intraday S/R
Monitor range position for mean reversion trades
Use proximity alerts for entry timing
Position Trading
Extended lookback reveals major structural levels
Touch count validation ensures reliability
Range position helps time accumulation/distribution
Risk Management
Distance metrics help size positions appropriately
Strong levels (high touch count) for tight stops
Midpoint line for partial profit taking
⚙️ Settings Guide
Core Settings
Lookback Period: Start with 100 for swing trading, 50 for day trading
Pivot Strength: Higher values = fewer but stronger levels
Max Levels: 2-3 support and 2-3 resistance recommended
Min Distance: 1.0% prevents clustering, increase for volatile assets
Zone Settings
Zone Width: 0.25% default works well for most assets
Zone Style: "Both" for maximum visibility
Extend Zones: Keep enabled to track levels forward
Transparency: 85% provides good visibility without clutter
Level Strength
Show Level Strength: Enable for color-coded importance
Min Touches: 2-3 for validated levels
Touch Detection: 0.3% for precise levels, increase for volatile markets
Visual Settings
Label Size: Small/Normal for most charts
Show Touch Count: Enable to see level validation
Line Width: 2 for standard, 3-4 for presentation charts
📈 Best Practices
Start Conservative: Begin with default settings, adjust based on asset volatility
Combine Timeframes: Use different lookback periods on multiple charts
Respect Strong Levels: Higher touch counts indicate institutional interest
Watch Range Position: <30% = near support, >70% = near resistance
Use Alerts: Set proximity alerts to avoid constant chart watching
Validate Breaks: Zone width shows where true breaks occur vs. fakeouts
🚀 What Makes This Different
Unlike basic pivot indicators that simply mark highs/lows:
✅ Validates levels through touch count analysis
✅ Ranks levels by actual strength, not just recency
✅ Visualizes zones, not just lines
✅ Quantifies your position within market structure
✅ Extends lookback far beyond standard limits
✅ Separates support and resistance controls
🎓 Tips for New Users
First Time Setup:
Add indicator to chart
Enable dashboard in settings (default on)
Observe which levels price respects
Adjust lookback/strength to match your trading style
Set proximity alerts for your key levels
Optimization:
Forex: 0.2-0.3% zone width, 100-200 lookback
Stocks: 0.3-0.5% zone width, 50-150 lookback
Crypto: 0.4-0.6% zone width, 100-200 lookback
Indices: 0.2-0.4% zone width, 100-250 lookback
⚠️ Disclaimer
This indicator is a technical analysis tool and should not be used as the sole basis for trading decisions. Support and resistance levels are not guarantees of price behavior. Always use proper risk management, combine with other analysis methods, and consider fundamental factors. Past performance does not guarantee future results.
Evil's Two Legged IndicatorIndicator that's used to identify 2-legged scalping setups, it's got some good options for channels and chop filtering.






















