Entropy Divergence (No Repaint) [PhenLabs]📊 Entropy Divergence (No Repaint)
Version: PineScript™ v6
📌 Description
The Entropy Divergence Scalper (EDS) is a sophisticated trading indicator that applies information theory to market analysis. By calculating Shannon Entropy on price returns, it identifies periods when market behavior becomes more predictable and orderly—the ideal conditions for divergence-based trading.
Traditional divergence indicators generate signals regardless of market conditions, leading to many false signals during chaotic, high-entropy periods. EDS solves this by acting as an intelligent filter: it only triggers signals when entropy drops below your specified threshold, indicating that the market has entered a more structured, tradeable state.
This indicator is built with a strict non-repainting guarantee. All signals use barstate.isconfirmed and only appear after bar close, giving you reliable signals you can trust for live trading.
🚀 Points of Innovation
Shannon Entropy integration measures market randomness using information theory mathematics
Dual divergence engine detects both RSI and Volume divergences simultaneously
Entropy-filtered signals eliminate noise by only triggering in low-entropy (predictable) market conditions
100% non-repainting architecture ensures all signals are confirmed and historically accurate
Multi-layer confirmation combines entropy state, RSI divergence, and volume divergence for higher probability setups
Dynamic color visualization provides instant visual feedback on current market entropy state
🔧 Core Components
Shannon Entropy Calculator: Bins price returns into histograms and calculates entropy using H(X) = -Σ p(x) × log₂(p(x))
RSI Divergence Detector: Identifies when price makes lower lows while RSI makes higher lows (bullish) or price makes higher highs while RSI makes lower highs (bearish)
Volume Divergence Detector: Spots increasing volume interest at price lows (bullish) or decreasing conviction at price highs (bearish)
Pivot Detection System: Uses configurable lookback periods to identify and track price, RSI, and volume pivots
Signal Classification Engine: Labels signals as RSI, VOL, or RSI+VOL based on which divergences triggered
🔥 Key Features
Entropy Threshold Control: Set your preferred entropy level (default 2.5) to filter out signals during chaotic market periods
Configurable Smoothing: EMA smoothing on entropy values reduces noise while maintaining signal responsiveness
Flexible Pivot Detection: Adjust left/right lookback bars to tune sensitivity for different trading styles
Divergence Search Range: Control how far back the indicator looks for divergence patterns (20-200 bars)
Minimum Pivot Distance: Prevents false signals from pivots that are too close together
Complete Alert System: Four alert conditions for bullish signals, bearish signals, any signal, and low entropy zone entry
🎨 Visualization
Dynamic Entropy Line: Color gradient shifts from green (low entropy/tradeable) to orange (high entropy/chaotic)
Entropy Threshold Line: Dashed reference line shows your configured entropy threshold
Low Entropy Zone Fill: Background highlighting indicates when market is in tradeable low-entropy state
Scaled RSI Plot: RSI overlay scaled to fit the entropy pane for easy correlation analysis
Normalized Volume Bars: Volume displayed as columns normalized against 20-period average
Signal Labels: Clear LONG/SHORT labels with divergence type (RSI, VOL, or RSI+VOL)
Information Table: Real-time display of entropy value, state, RSI, and current signal status
📖 Usage Guidelines
Entropy Lookback Period — Default: 20, Range: 5-100 — Controls how many bars are used for entropy calculation; higher values provide smoother readings but slower response
Histogram Bins — Default: 10, Range: 5-50 — Number of bins for probability distribution; more bins provide finer granularity
Low Entropy Threshold — Default: 2.5, Range: 0.5-4.0 — Signals only trigger when entropy drops below this value; lower settings are more selective
Entropy Smoothing — Default: 3, Range: 1-10 — EMA smoothing applied to raw entropy values for noise reduction
RSI Length — Default: 14, Range: 5-50 — Standard RSI calculation period
Pivot Lookback Left — Default: 5, Range: 2-20 — Bars to the left for pivot detection
Pivot Lookback Right — Default: 2, Range: 1-10 — Bars to the right for pivot confirmation; lower values produce faster signals
Divergence Search Range — Default: 60, Range: 20-200 — Maximum bars to look back for divergence comparison
Min Bars Between Pivots — Default: 5, Range: 3-30 — Minimum distance between pivots for valid divergence detection
✅ Best Use Cases
Scalping during low-volatility consolidation periods when entropy drops and price becomes more predictable
Swing trade entry timing by waiting for divergence signals in low-entropy market conditions
Trend reversal identification when both RSI and Volume divergences align with low entropy readings
Multi-timeframe confirmation by checking entropy state on higher timeframes before taking signals
Filtering existing strategies by adding entropy as a confirmation layer to reduce false signals
⚠️ Limitations
Signals appear with a delay due to pivot confirmation requirements (pivotLookbackRight bars after pivot forms)
May generate fewer signals during strongly trending markets where entropy remains elevated
Entropy threshold requires optimization for different instruments and timeframes
Not designed for high-frequency trading due to bar-close confirmation requirement
Divergences can fail in extremely strong trends where momentum overwhelms the signal
💡 What Makes This Unique
First indicator to combine Shannon Entropy filtering with multi-factor divergence detection
Information theory approach provides mathematical foundation for identifying tradeable market states
Triple confirmation requirement (low entropy + divergence + bar close) significantly reduces false signals
Non-repainting guarantee makes it suitable for strategy backtesting and live trading
Open-source PineScript v6 code allows traders to understand and customize the methodology
🔬 How It Works
Step 1 — Entropy Calculation: The indicator calculates logarithmic returns, bins them into a histogram, and computes Shannon Entropy to measure market randomness
Step 2 — Entropy Filtering: When smoothed entropy drops below the threshold, the market is considered to be in a tradeable low-entropy state
Step 3 — Pivot Detection: The system continuously tracks price, RSI, and volume pivots using configurable lookback parameters
Step 4 — Divergence Analysis: When a new pivot is confirmed, the indicator compares it against previous pivots to detect bullish or bearish divergences
Step 5 — Signal Generation: A final signal only triggers when low entropy conditions coincide with a confirmed divergence pattern on a closed bar
💡 Note:
This indicator is designed for educational purposes and technical analysis. Always use proper risk management and never risk more than you can afford to lose. The non-repainting guarantee means signals will only appear after bar close—watch the indicator in real-time to verify this behavior. For optimal results, consider combining EDS signals with support/resistance levels and overall market context.
Statistics
Volume Profile Skew [BackQuant]Volume Profile Skew
Overview
Volume Profile Skew is a market-structure indicator that answers a specific question most volume profiles do not:
“Is volume concentrating toward lower prices (accumulation) or higher prices (distribution) inside the current profile range?”
A standard volume profile shows where volume traded, but it does not quantify the shape of that distribution in a single number. This script builds a volume profile over a rolling lookback window, extracts the key profile levels (POC, VAH, VAL, and a volume-weighted mean), then computes the skewness of the volume distribution across price bins. That skewness becomes an oscillator, smoothed into a regime signal and paired with visual profile plotting, key level lines, and historical POC tracking.
This gives you two layers at once:
A full profile and its important levels (where volume is).
A skew metric (how volume is leaning within that range).
What this indicator is based on
The foundation comes from classical “volume at price” concepts used in Market Profile and Volume Profile analysis:
POC (Point of Control): the price level with the highest traded volume.
Value Area (VAH/VAL): the zone containing the bulk of activity, commonly 70% of total volume.
Volume-weighted mean (VWMP in this script): the average price weighted by volume, a “center of mass” for traded activity.
Where this indicator extends the idea is by treating the volume profile as a statistical distribution across price. Once you treat “volume by price bin” as a probability distribution (weights sum to 1), you can compute distribution moments:
Mean: where the mass is centered.
Standard deviation: how spread-out it is.
Skewness: whether the distribution has a heavier tail toward higher or lower prices.
This is not a gimmick. Skewness is a standard statistic in probability theory. Here it is applied to “volume concentration across price”, not to returns.
Core concept: what “skew” means in a volume profile
Imagine a profile range from Low to High, split into bins. Each bin has some volume. You can get these shapes:
Balanced profile: volume is fairly symmetric around the mean, skew near 0.
Bottom-heavy profile: more volume at lower prices, with a tail toward higher prices, skew tends to be positive.
Top-heavy profile: more volume at higher prices, with a tail toward lower prices, skew tends to be negative.
In this script:
Positive skew is labeled as ACCUMULATION.
Negative skew is labeled as DISTRIBUTION.
Near-zero skew is NEUTRAL.
Important: accumulation here does not mean “buying will immediately pump price.” It means the profile shape suggests more participation at lower prices inside the current lookback range. Distribution means participation is heavier at higher prices.
How the volume profile is built
1) Define the analysis window
The profile is computed on a rolling window:
Lookback Period: number of bars included (capped by available history).
Profile Resolution (bins): number of price bins used to discretize the high-low range.
The script finds the highest high and lowest low in the lookback window to define the price range:
rangeHigh = highest high in window
rangeLow = lowest low in window
binSize = (rangeHigh - rangeLow) / bins
2) Create bin midpoints
Each bin gets a midpoint “price” used for calculations:
price = rangeLow + binSize * (b + 0.5)
These midpoints are what the mean, variance, and skewness are computed on.
3) Distribute each candle’s volume into bins
This is a key implementation detail. Real volume profiles require tick-level data, but Pine does not provide that. So the script approximates volume-at-price using candle ranges:
For each bar in the lookback:
Determine which bins its low-to-high range touches.
Split that candle’s total volume evenly across the touched bins.
So if a candle spans 6 bins, each bin gets volume/6 from that bar. This is a practical, consistent approximation for “where trading could have occurred” inside the bar.
This approach has tradeoffs:
It does not know where within the candle the volume truly traded.
It assumes uniform distribution across the candle range.
It becomes more meaningful with larger samples (bigger lookback) and/or higher timeframes.
But it is still useful because the purpose here is the shape of the distribution across the whole window, not exact microstructure.
Key profile levels: POC, VAH, VAL, VWMP
POC (Point of Control)
POC is found by scanning bins and selecting the bin with maximum volume. The script stores:
pocIndex: which bin has max volume
poc price: midpoint price of that bin
Value Area (VAH/VAL) using 70% volume
The script builds the value area around the POC outward until it captures 70% of total volume:
Start with the POC bin.
Expand one bin at a time to the side with more volume.
Stop when accumulated volume >= 70% of total profile volume.
Then:
VAL = rangeLow + binSize * lowerIdx
VAH = rangeLow + binSize * (upperIdx + 1)
This produces a classic “where most business happened” zone.
VWMP (Volume-Weighted Mean Price)
This is essentially the center of mass of the profile:
VWMP = sum(price * volume ) / totalVolume
It is similar in spirit to VWAP, but it is computed over the profile bins, not from bar-by-bar typical price.
Skewness calculation: turning the profile into an oscillator
This is the main feature.
1) Treat volumes as weights
For each bin:
weight = volume / totalVolume
Now weights sum to 1.
2) Compute weighted mean
Mean price:
mean = sum(weight * price )
3) Compute weighted variance and std deviation
Variance:
variance = sum(weight * (price - mean)^2)
stdDev = sqrt(variance)
4) Compute weighted third central moment
Third moment:
m3 = sum(weight * (price - mean)^3)
5) Standardize to skewness
Skewness:
rawSkew = m3 / (stdDev^3)
This standardization matters. Without it, the value would explode or shrink based on profile scale. Standardized skewness is dimensionless and comparable.
Smoothing and regime rules
Raw skewness can be jumpy because:
profile bins change as rangeHigh/rangeLow shift,
one high-volume candle can reshape the distribution,
volume regimes change quickly in crypto.
So the indicator applies EMA smoothing:
smoothedSkew = EMA(rawSkew, smooth)
Then it classifies regime using fixed thresholds:
Bullish (ACCUMULATION): smoothedSkew > +0.25
Bearish (DISTRIBUTION): smoothedSkew < -0.25
Neutral: between those values
Signals are generated on threshold cross events:
Bull signal when smoothedSkew crosses above +0.25
Bear signal when smoothedSkew crosses below -0.25
This makes the skew act like a regime oscillator rather than a constantly flipping color.
Volume Profile plotting modes
The script draws the profile on the last bar, using boxes for each bin, anchored to the right with a configurable offset. The width of each profile bar is normalized by max bin volume:
volRatio = binVol / maxVol
barWidth = volRatio * width
Three style modes exist:
1) Gradient
Uses a “jet-like” gradient based on volRatio (blue → red). Higher-volume bins stand out naturally. Transparency increases as volume decreases, so low-volume bins fade.
2) Solid
Uses the current regime color (bull/bear/neutral) for all bins, with transparency. This makes the profile read as “structure + regime.”
3) Skew Highlight
Highlights bins that match the skew bias:
If skew bullish, emphasize lower portion of profile.
If skew bearish, emphasize higher portion of profile.
Else, keep most bins neutral.
This is a visual “where the skew is coming from” mode.
Historical POC tracking and Naked POCs
This script also treats POCs as meaningful levels over time, similar to how traders track old VA levels.
What is a “naked POC”?
A “naked POC” is a previously formed POC that has not been revisited (retested) by price since it was recorded. Many traders watch these as potential reaction zones because they represent prior “maximum traded interest” that the market has not re-engaged with.
How this script records POCs
It stores a new historical POC when:
At least updatebars have passed since the last stored POC, and
The POC has changed by at least pochangethres (%) from the last stored value.
New stored POCs are flagged as naked by default.
How naked becomes tested
On each update, the script checks whether price has entered a small zone around a naked POC:
zoneSize = POC * 0.002 (about 0.2%)
If bar range overlaps that zone, mark it as tested (not naked).
Display controls:
Highlight Naked POCs: draws and labels untested POCs.
Show Tested POCs: optionally draw tested ones in a muted color.
To avoid clutter, the script limits stored POCs to the most recent 20 and avoids drawing ones too close to the current POC.
On-chart key levels and what they mean
When enabled, the script draws the current lookback profile levels on the price chart:
POC (solid): the “most traded” price.
VAH/VAL (dashed): boundaries of the 70% value area.
VWMP (dotted): volume-weighted mean of the profile distribution.
Interpretation framework (practical, not mystical):
POC often behaves like a magnet in balanced conditions.
VAH/VAL define the “accepted” area, breaks can signal auction continuation.
VWMP is a fair-value reference, useful as a mean anchor when skew is neutralizing.
Oscillator panel and histogram
The skew oscillator is plotted in a separate pane:
Line: smoothedSkew, colored by regime.
Histogram: smoothedSkew as bars, colored by sign.
Fill: subtle shading above/below 0 to reinforce bias.
This makes it easy to read:
Direction of bias (positive vs negative).
Strength (distance from 0 and from thresholds).
Transitions (crosses of ±0.25).
Info table: what it summarizes
On the last bar, a table prints key diagnostics:
Current skew value (smoothed).
Regime label (ACCUMULATION / DISTRIBUTION / NEUTRAL).
Current POC, VAH, VAL, VWMP.
Count of naked POCs still active.
A simple “volume location” hint (lower/higher/balanced).
This is designed for quick scanning without reading the entire profile.
Alerts
The indicator includes alerts for:
Skew regime shifts (cross above +0.25, cross below -0.25).
Price crossing above/below current POC.
Approaching a naked POC (within 1% of any active naked POC).
The “approaching naked POC” alert is useful as a heads-up that price is entering a historically important volume magnet/reaction zone.
How to use it properly
1) Regime filter
Use skew regime to decide what type of trades you should prioritize:
ACCUMULATION (positive skew): market activity is heavier at lower prices, pullbacks into value or below VWMP often matter more.
DISTRIBUTION (negative skew): activity is heavier at higher prices, rallies into value or above VWMP often matter more.
NEUTRAL: mean-reversion and POC magnet behavior tends to dominate.
This is not “buy when green.” It is context for what the auction is doing.
2) Level-based execution
Combine skew with VA/POC levels:
In neutral regimes, expect rotations around POC and inside VA.
In strong skew regimes, watch for acceptance away from POC and reactions at VA edges.
3) Naked POCs as targets and reaction zones
Naked POCs can act like unfinished business. Common workflows:
As targets in rotations.
As areas to reduce risk when price is approaching.
As “if it breaks cleanly, trend continuation” markers when price returns with force.
Parameter tuning guidance
Lookback
Controls how “local” the profile is.
Shorter: reacts faster, more sensitive to recent moves.
Longer: more stable, better for swing context.
Bins
Controls resolution of the profile.
Higher bins: more detail, more computation, more sensitive profile shape.
Lower bins: smoother, less detail, more stable skew.
Smoothing
Controls how noisy the skew oscillator is.
Higher smoothing: fewer regime flips, slower response.
Lower smoothing: more responsive, more false transitions.
POC tracking settings
Update interval and threshold decide how many historical POCs you store and how different they must be. If you set them too loose, you will spam levels. If too strict, you will miss meaningful shifts.
Limitations and what not to assume
This indicator uses candle-range volume distribution because Pine cannot see tick-level volume-at-price. That means:
The profile is an approximation of where volume could have traded, not exact tape data.
Skew is best treated as a structural bias, not a precise signal generator.
Extreme single-bar events can distort the distribution briefly, smoothing helps but cannot remove reality.
Summary
Volume Profile Skew takes standard volume profile structure (POC, Value Area, volume-weighted mean) and adds a statistically grounded measure of profile shape using skewness. The result is a regime oscillator that quantifies whether volume concentration is leaning toward lower prices (accumulation) or higher prices (distribution), while also plotting the full profile, key levels, and historical naked POCs for actionable context.
Pattern Atlas Smart Panel Alerts Toni Ventura MaltaThe Pattern Atlas in 1 Indicator
Not fool proof but helps understanding what the discord traders are talking about ;)
DafeUltimateLibDAFE Ultimate Library: The Universal AI Dashboard & Analysis System
This is the operating system for your next generation of trading tools. Welcome to the future of on-chart intelligence.
█ PHILOSOPHY: BEYOND THE INDICATOR, INTO THE CONSCIOUSNESS
For decades, technical analysis has been a monologue. We load indicators onto our charts, and they give us static, one-dimensional answers: a line, a number, a crossover. They provide data, but they offer no wisdom, no context, no actionable intelligence. They are tools without a mind.
The DAFE Ultimate Library was created to fundamentally shatter this paradigm. It was not designed to be another indicator, but to be the very brain that powers all of your future indicators. This is a professional-grade, open-source library that allows any Pine Script developer to integrate a sophisticated, AI-powered analytical and visualization engine into their own scripts with just a few lines of code.
This library transforms your indicator from a simple data plotter into an intelligent trading assistant. It takes in raw metrics—RSI, MACD, Volume, Volatility—and synthesizes them into a rich, multi-dimensional analysis, complete with a primary bias, confidence score, market state assessment, and a set of dynamic, actionable recommendations. It doesn't just give you the "what"; it gives you the " so what? "
█ WHAT IS THIS LIBRARY? A REVOLUTION IN PINE SCRIPT
This is a foundational shift in what's possible within the TradingView ecosystem.
A Universal AI Brain: At its core is a powerful analysis engine. You feed it any number of metrics from your own custom script—each with its own type (bounded, zero-centric, trend, etc.) and weight—and the AI synthesizes them into a single, cohesive analysis. It's like having a quantitative analyst living inside your indicator.
The ASCII Art Visualization Core: This is the soul of the library. We have pushed the boundaries of what's possible with Pine Script's table and label objects to create a stunning, fully animated, and customizable ASCII art interface. This is not a gimmick; it is a high-information-density display that brings your data to life in a way that is both beautiful and intuitively understandable. Choose from multiple "genders" (Male, Female, Droid) and themes to create an AI assistant that fits your personal aesthetic.
Open & Extensible Framework: This is a library, not a closed black box. It is designed to be the foundation for a new generation of "smart" indicators. I provide a simple, powerful API (Application Programming Interface) that allows any developer to plug their own unique metrics into the DAFE AI brain and instantly gain access to its analytical and visualization power.
Human-Readable Intelligence: The output is not just numbers. The AI communicates in natural language. It provides you with its "Thoughts" ("Bullish momentum across 3 metrics," "Structural weakness developing") and a set of "Recommended Actions" ("ACCUMULATE on pullbacks," "TIGHTEN stops") that adapt in real-time to the changing market conditions.
█ HOW IT WORKS: THE ARCHITECTURE OF AN AI
The library operates on a simple but powerful three-stage pipeline.
Stage 1: Metric Ingestion (The Senses)
As a developer, you first define the "senses" of your AI. Using the library's simple create_metric functions, you tell the AI what to look at. This is a highly flexible system that can handle any type of data your indicator produces. You define the metric's name, its current value, its "mode" of operation, and its relative importance (weight). The available modes allow the AI to correctly interpret any data source:
metric_bounded: For oscillators like RSI or Stochastics that move between set levels (e.g., 0-100).
metric_zero: For indicators like MACD or a Momentum oscillator that fluctuate around a central zero line.
metric_trend: For moving averages or trend lines, analyzing their position relative to price.
metric_volume / metric_volatility: Specialized metrics for analyzing volume and volatility events against high/low thresholds.
Stage 2: The Analysis Engine (The Brain)
On every bar, the library takes the updated metric values and feeds them into its core analytical model. This is where the magic happens.
Normalization: Each metric is processed according to its "mode" and converted into a standardized signal score from -100 (extremely bearish) to +100 (extremely bullish). This allows the AI to compare apples and oranges—an RSI of 80 can now be directly compared to a MACD histogram of 0.5.
Synthesis: The AI calculates a composite score by taking a weighted average of all the individual metric signals. This gives a single, unified view of the market's state based on all available evidence.
State Assessment: It analyzes the distribution of signals (how many are bullish vs. bearish), the number of "extreme" readings (e.g., overbought, high volume), and the overall composite score to determine the current Market State (e.g., "STRONG TREND," "MIXED SIGNALS," "EXTREME CONDITIONS").
Confidence Calculation: The magnitude of the final composite score is translated into a Confidence percentage, representing the strength of the AI's conviction in its current bias.
Natural Language Generation: Based on the final analysis, the engine selects the most appropriate "Thoughts" and "Recommended Actions" from its pre-programmed library of strategic heuristics, providing you with context and a potential game plan.
Stage 3: The Rendering Engine (The Face)
The final analysis is passed to the visualization core, which renders the complete AI Terminal on your chart. This is a masterwork of Pine Script's drawing capabilities.
The Face: The stunning ASCII art face is dynamically generated on every bar. Its Mood (Confident, Focused, Cautious, etc.) is directly determined by the AI's confidence level. Its eyes will even animate with a subtle, customizable Blink cycle, bringing the character to life and creating an unparalleled user experience.
The Dashboard: The surrounding terminal is built, displaying the primary bias, market state, confidence, and the detailed thoughts, active metrics, and recommended actions in a clean, retro-futuristic interface.
Theming: The entire display is colored according to your chosen theme, from the cool greens of "Matrix" to the vibrant pinks of "Neon," allowing for deep personalization.
█ A GUIDE FOR DEVELOPERS: INTEGRATING THE DAFE AI
We have made it incredibly simple to bring your indicators to life with the DAFE AI. This is the true purpose of the library—to empower you.
Import the Library: Add the following line to the top of your script import DskyzInvestments/DafeUltimateLib/1 as dafe
Define Your Metrics: In the barstate.isfirst block of your script, create an array and populate it with the metrics your indicator uses. For example:
var array my_metrics = array.new()
if barstate.isfirst
array.push(my_metrics, dafe.metric_bounded("RSI", 50.0, 70.0, 30.0, 1.5))
array.push(my_metrics, dafe.metric_zero("MACD Hist", 0.0, 0.5, 1.0))
Update Your Metrics: On every bar, update the values of your metrics.
dafe.update_metric(array.get(my_metrics, 0), ta.rsi(close, 14))
dafe.update_metric(array.get(my_metrics, 1), macd_histogram_value)
Configure & Render: Create a configuration object from user inputs and call the main render function.
dafe.DafeConfig my_config = dafe.quick_config("Droid", "Cyber")
dafe.render(my_metrics, my_config)
That's it. With these few steps, you have integrated a complete AI dashboard and analysis engine directly into your own script, saving you hundreds of hours of development time and providing your users with a revolutionary interface.
█ DEVELOPMENT PHILOSOPHY
The DAFE Ultimate Library was born from a desire to push the boundaries of Pine Script and to empower the entire TradingView developer community. We believe that the future of technical analysis is not just in creating more complex algorithms, but in building more intelligent and intuitive ways to interact with the data those algorithms provide. This library is our contribution to that future. It is an open-source tool designed to elevate the work of every developer who uses it, fostering a new era of "smart" indicators on the platform.
This library is designed to help you and your users make the best trades by providing a layer of objective, synthesized intelligence that filters out noise, quantifies confidence, and promotes a disciplined, analytical approach to the market.
█ A NOTE TO USERS & DISCLAIMER
THIS IS A LIBRARY: This script does nothing on its own. It is a powerful engine that must be integrated by other indicator developers. It is a tool for builders.
THE AI IS A GUIDE, NOT A GURU: The analysis provided is based on the mathematical synthesis of the metrics it is fed. It is a powerful decision-support tool, but it is not a crystal ball. All trading involves substantial risk.
GARBAGE IN, GARBAGE OUT: The quality of the AI's analysis is directly dependent on the quality and logic of the metrics it is given by the host indicator.
"The goal of a successful trader is to make the best trades. Money is secondary."
— Alexander Elder
Taking you to school. - Dskyz, Trade with DAFE.
TSM: Time-Series Momentum & Volatility Targeting [Moskowitz]TSM: Institutional Time-Series Momentum & Volatility Targeting (Moskowitz)
SUMMARY
TSM is a trend and risk-sizing indicator designed to convert price movement into a risk-adjusted regime signal and a single Recommended Exposure output. It addresses a common trend problem: direction can be correct while sizing is wrong during volatility expansions.
Recommended Exposure is a signed value where positive indicates bullish bias and negative indicates bearish bias. The magnitude reflects confidence after the volatility and quality filters are applied.
The engine combines volatility-scaled time-series momentum across multiple horizons with optional volatility targeting and an optional efficiency filter to reduce noise sensitivity and improve sizing discipline.
WHAT THIS INDICATOR GIVES YOU
A risk-adjusted momentum signal that is scaled by realized volatility rather than raw returns, so high-volatility noise is less likely to look like strong trend.
An optional volatility targeting layer that mechanically scales Recommended Exposure down when realized volatility rises and up when it falls, capped by Max Leverage.
An ensemble approach using fast, medium, and slow horizons with configurable weights, reducing dependence on a single lookback and lowering curve-fitting risk.
An optional R-squared efficiency filter that reduces exposure in choppy, low-quality trends, with a floor to avoid over-suppressing exposure.
Optional workflow features including a dashboard, trend cloud bands, threshold-based signals with cooldown, and alerts.
SCIENTIFIC FOUNDATION (PLAIN ENGLISH)
Time-Series Momentum (Moskowitz, Ooi, Pedersen 2012) describes the empirical tendency for an asset’s own past returns to predict its future returns in expectation, distinct from cross-sectional momentum which compares assets to each other.
Volatility clustering means markets alternate between calm and violent regimes; many traditional trend tools misread volatility shocks as sustainable trend. This indicator normalizes momentum by realized volatility to express trend significance relative to the regime.
Volatility targeting (Harvey et al. 2018) scales exposure inversely to realized volatility to stabilize risk. When volatility rises, recommended exposure is reduced mechanically; when volatility falls, exposure can increase, subject to a max leverage cap.
DATA AND SOURCES
This indicator uses only the chart symbol’s OHLC data. No external feeds, no COT libraries, and no third-party data sources are required.
It supports multi-timeframe calculation. You can compute the signal on the current chart timeframe, or use a fixed timeframe such as Daily to keep volatility math consistent when viewing intraday charts.
HOW THE ENGINE WORKS (HIGH LEVEL)
Step 1 estimates realized volatility from log returns over a chosen lookback. Step 2 computes a volatility-scaled momentum statistic for three horizons (fast, medium, slow) to measure how meaningful the move is relative to volatility. Step 3 clamps extreme values so outliers do not dominate. Step 4 combines the horizons into a weighted ensemble. Step 5 optionally applies an efficiency filter to reduce exposure in choppy trends. Step 6 optionally applies volatility targeting to scale exposure inversely with realized annualized volatility, capped by Max Leverage. The final output is Recommended Exposure as the combined result of direction, risk scaling, and quality filtering.
OUTPUTS AND HOW USERS SHOULD APPLY THEM
Recommended Exposure is the primary output. Positive values indicate bullish regime bias, negative values indicate bearish regime bias, and larger magnitude indicates higher risk-adjusted conviction after filters.
Typical use is as a position-sizing overlay: keep your own entry method and use Recommended Exposure to decide how aggressive or defensive sizing should be in the current regime.
Signals are optional and trigger when Recommended Exposure crosses user-defined thresholds. A cooldown reduces repeated triggers during consolidations, and direction can be restricted to long only, short only, or both.
The dashboard is optional and displays realized volatility versus target, ensemble momentum, the efficiency metric, the volatility scalar, the quality multiplier, and final Recommended Exposure, including the fast/medium/slow breakdown.
Trend cloud bands are optional and provide range context; they are not the signal and are intended as visual regime support.
SETTINGS GUIDE (WHAT MATTERS MOST)
Fixed Timeframe mode is recommended for consistent volatility math across chart timeframes; Current Chart mode is more sensitive to the displayed timeframe.
Momentum horizons control responsiveness versus stability. Shorter lookbacks react faster but whipsaw more; longer lookbacks are smoother but slower. Weights allow emphasizing fast responsiveness or slow regime confirmation.
Volatility targeting turns the tool into a sizing engine by scaling exposure inversely to realized volatility. Target annualized volatility sets the risk budget, and the annualization basis (365 vs 252) aligns conventions for crypto versus traditional markets. Max Leverage caps the scalar in very low-volatility regimes.
The efficiency filter reduces exposure in choppy conditions; the floor controls how harshly exposure is reduced. Threshold and cooldown control how selective discrete signals are.
LIMITATIONS (IMPORTANT FOR USERS)
This is a trend-following framework, so it will lag turning points by design. Sideways markets can still cause whipsaws; cooldown and the efficiency filter may reduce but cannot eliminate this. Volatility targeting can reduce drawdowns during volatility expansions but may reduce participation during sharp V-shaped reversals after volatility increases. The efficiency metric is a practical proxy for trend straightness and can misclassify certain price paths.
REFERENCES
Moskowitz, T. J., Ooi, Y. H., and Pedersen, L. H. (2012). Time series momentum. Journal of Financial Economics, 104(2), 228-250.
Harvey, C. R., Rattray, S., Sinclair, A., and Van Hemert, O. (2018). The impact of volatility targeting. Journal of Portfolio Management, 45(1), 14-33.
Hurst, B., Ooi, Y. H., and Pedersen, L. H. (2017). A century of evidence on trend-following investing. Journal of Portfolio Management, 44(1), 15-29.
DISCLAIMER
Educational and informational purposes only. Not financial advice. Trading involves risk. Past performance is not indicative of future results.
MJ amd tableAsia, Londong and New york table showing each session what goes to happen depending on the movement of AMD
Z-Score ProZ-Score Pro - Complete Description
This is an **advanced mean reversion indicator** that measures how many standard deviations the current price is from its average. It's ideal for identifying market extremes and trading opportunities.
What is the Z-Score?
The Z-Score is a statistical measure that answers: **"How far is the price from normal?"**
- **Z = 0**: Price is at its average
- **Z = +2**: Price is 2 standard deviations above (overbought)
- **Z = -2**: Price is 2 standard deviations below (oversold)
- **Z > +3** or **Z < -3**: Very rare extremes (occur ~0.3% of the time)
Main Features
### 1. **Flexible Calculation**
- **SMA or EMA**: Choose between simple or exponential moving average
- **Adjustable period**: Default 20 periods
- **Smoothing**: Option to smooth the Z-Score to reduce noise
### 2. **Multiple Levels**
- **±1.0**: Caution zone
- **±2.0**: Overbought/Oversold (68% statistical confidence)
- **±3.0**: Rare extremes (99.7% statistical confidence)
### 3. **Trading Signals**
The indicator generates automatic signals based on:
**Buy Signals (BUY)**:
- Z-Score is in oversold zone
- Momentum changes from negative to positive (price stops falling)
**Sell Signals (SELL)** :
- Z-Score is in overbought zone
- Momentum changes from positive to negative (price stops rising)
**Aggressiveness Levels**:
- **Conservative**: Only signals at extremes (±3.0)
- **Normal**: Signals at ±2.0 (recommended)
- **Aggressive**: More frequent signals at ±1.5
### 4. **Divergence Detection**
**Bullish Divergence** (aqua marker):
- Price makes a lower low
- Z-Score makes a higher low
- Indicates weakening of downtrend
**Bearish Divergence** (fuchsia marker):
- Price makes a higher high
- Z-Score makes a lower high
- Indicates weakening of uptrend
---
## Visualization
### Dynamic Colors
- **Bright red**: Z-Score > 2 and rising (strong overbought)
- **Orange**: Z-Score > 1 and rising
- **Purple**: Neutral zone rising
- **Transparent green**: Z-Score falling (any level)
### Background Zones
- **Intense red**: Extreme overbought (Z > 3)
- **Soft orange**: Overbought (Z > 2)
- **Intense green**: Extreme oversold (Z < -3)
- **Soft lime**: Oversold (Z < -2)
### Info Table (top right corner)
Shows in real-time:
- **Current Z-Score**: Numeric value with color
- **Status**: Extreme OB/OS, Overbought, Oversold, or Neutral
- **Momentum**: Rising ↗ or Falling ↘
- **Mean**: Current average value
- **Std Dev**: Current standard deviation
---
## Alert System
The indicator includes **8 types of alerts**:
1. **Buy Signal**: When entry conditions are met
2. **Sell Signal**: When exit conditions are met
3. **Overbought**: When crossing above +2.0
4. **Oversold**: When crossing below -2.0
5. **Extreme Overbought**: When reaching +3.0
6. **Extreme Oversold**: When reaching -3.0
7. **Bullish Divergence**: Potential reversal up
8. **Bearish Divergence**: Potential reversal down
---
## How to Use It
### **Mean Reversion Strategy**
1. Wait for Z-Score to reach ±2 or beyond
2. Wait for BUY/SELL signal (momentum reversal)
3. Enter trade in opposite direction of extreme
4. Exit when Z-Score returns to zero
### **Divergence Strategy**
1. Identify divergence markers (DIV)
2. Confirm with momentum change
3. Enter in direction of divergence
4. Use Z-Score levels as targets
### **Multi-Timeframe Analysis**
- **Short-term** (5-15 min): Scalping with aggressive mode
- **Medium-term** (1H-4H): Swing trading with normal mode
- **Long-term** (Daily): Position trading with conservative mode
---
## Best Practices
**Do**:
- Use in ranging/sideways markets
- Combine with support/resistance levels
- Wait for momentum confirmation
- Use conservative mode in trending markets
**Don't**:
- Trade against strong trends
- Ignore divergences
- Use alone without confirmation
- Over-trade in low volatility
---
## Statistical Background
The Z-Score follows a **normal distribution**:
- **68%** of values fall within ±1 standard deviation
- **95%** of values fall within ±2 standard deviations
- **99.7%** of values fall within ±3 standard deviations
When price reaches Z = ±2, there's a **95% probability** it will revert toward the mean, making it a powerful mean reversion tool.
---
##Customization Options
All aspects are customizable:
- Calculation method and periods
- Visual colors and transparency
- Signal sensitivity
- Alert preferences
- Level thresholds
- Background zones on/off
Wick Statistics (Intra-Day)Data box that shows smallest, largest, and average wick point size during specified time ranges.
Wick Ranges (GG)Simple data box that tracks candle wick largest, smallest, and average sizes by price within specified time ranges. Displays labels for upper and lower wicks of current candle.
Helpful if your entry model is entering on the close/open of momentum candles.
-GG
SPX & VIX Overnight Gap and Gap % w/VIX Open
Displays SPX and VIX Overnight gaps in points and percentage with VIX open value. Display boxes change color depending on gap up (green) or gap down (red) Optional vertical line which changes color depending on the gap direction placed at the first bar.
Dual Bollinger Band Zones (20,2 & 20,0.7)To Indentify Zone 1, Zone 2, Zone 3 and Zone 4
Tradeable zone: Zone 1 for Long and Zone 4 for Short
No Trade Zone: Zond 2 and Zone 3
LDEF SENS Loss Dependent Error Filter Dominance Regime SwitchCAPITALCOM:GOLD
LDEF SENS stands for Loss Dependent Error Filter. This indicator is a dominance regime filter with an adaptive switch boundary. It separates the market into two main states.
Directional tradeable tape (trend and impulse conditions)
Balanced noisy tape (higher fakeout probability)
It also provides a dominance direction bias (bull vs bear) and an adaptive boundary you can use as a market switch signal.
What you see in the indicator pane (bottom panel)
Main line (0 to 100): dominance sensitivity score
Line color meaning
Green: bullish dominance (L greater than R)
Red: bearish dominance (R greater than L)
Gray: low strength or mixed tape
Purple line: adaptive regime boundary (moving threshold)
Violet shading: regime ON (tradeable conditions)
Key idea: height equals strength, color equals direction, violet shading equals regime state.
How to read the three images
Image A - Regime ON in a trending environment
Where to look
Price panel: left to middle shows a clean up move
Indicator panel: directly below the same time window
Violet band is present for a sustained stretch
Main line stays high and mostly green
What it means
When the violet band stays ON, the tape is directional enough for trend following setups to have higher quality. This is not an entry signal. It is an environment filter.
Image B - Switch boundary and state changes
Where to look
Indicator panel: focus on the purple adaptive line and the main line crossing relative to it
Watch the moment the main line moves above the purple line. In the same region, violet shading turns ON.
What it means
The purple line is the adaptive regime boundary.
Cross above: regime switches toward directional tape (state change confirmation)
Cross below: regime fades and chop risk returns
Image C - Direction semantics inside a regime
Where to look
Indicator panel: inside violet shaded regions
Main line is green during bullish dominance (L greater than R)
Main line is red during bearish dominance (R greater than L)
What it means
Violet answers: is this a tradeable regime
Green or red answers: which side is dominating
Together, they provide a filter plus bias framework.
Practical usage
Regime filter
Prefer setups only when the violet band is ON
Reduce size or tighten criteria when the violet band is OFF
Direction bias
Prefer longs when the line is green
Prefer shorts when the line is red
Treat gray as no edge or mixed tape
Switch boundary analysis
Cross above purple: treat as regime shift confirmation
Cross below purple: treat as regime cooling off and higher chop risk
Limitations
This is a regime and dominance tool, not a standalone entry generator. Regime confirmation can be late by design, especially after shocks. Use it with structure, liquidity, and risk management.
KRXNameMapperLibrary "KRXNameMapper"
TODO: add library description here
getCompanyName(code)
TODO: add function description here
Parameters:
code (string)
Returns: TODO: add what function returns
Risk:Reward Tool Pro - MECTRADER (Minimalist)This is an optimized and refined version of my previous Risk/Reward tool. In this update, I have focused on visual clarity by removing all background color fills (shaded zones) to provide a much more minimalist and professional charting experience.
Key Improvements:
Zero Visual Distractions: All linefills have been removed, allowing traders to focus purely on price action and market structure without cluttered backgrounds.
Clean Aesthetics: Take Profit levels feature dashed lines for easy target identification, while Entry and Stop Loss levels remain solid for clear boundary definition.
Performance Focused: The script has been streamlined for a lightweight footprint, making it ideal for users who run multiple indicators simultaneously.
Core Features:
Tick-Based Calculation: Automatically calculate up to 5 Take Profit levels based on ticks.
Quick SL Setup: Simple input for Stop Loss distance.
Dynamic Labels: Real-time price display for every level on the right side of the chart.
Dual Mode: Full support for both Long and Short positions.
Designed for traders who demand technical precision without sacrificing the visual workspace.
ETF-CFD Ratio Bridge
This indicator helps traders visualize the relationship between ETFs and their corresponding CFD/Spot instruments. It allows you to trade on one chart while monitoring the equivalent price levels of the other instrument without mental math or switching screens.
Features
1. Ratio Table
A customizable table displayed on the chart (default: Top Right) that shows:
- Pair : The ETF and CFD pair being monitored.
- Ratio : The calculated price ratio (ETF / CFD).
- Prices : Real-time prices for both instruments.
2. Companion Price Label
A dynamic label that moves with the current price candle.
- Displays the equivalent price of the paired instrument.
- Example : If you are viewing SPY , the label shows the equivalent US500 price next to the candle.
3. Left Virtual Scale
A custom vertical axis drawn on the left side of the chart.
- Shows price levels for the companion instrument corresponding to the current visible chart range.
- Allows you to read "CFD prices" directly on an "ETF chart" (and vice versa) via the Y-axis.
4. Historical Levels lines
Visualizes recent market structure converted to the companion price.
- HH(x) : Highest High of the last X bars (default: 20).
- LL(x) : Lowest Low of the last X bars.
- Dashed lines extend to the right with labels showing the converted price at those key levels.
5. Closed Market Handling
Ensures the indicator remains useful even when the ETF market is closed (e.g., after hours) while the Futures/CFD market is open.
- Automatic Detection : The script detects if the ETF market is closed based on the timestamp.
- Fixed Ratio : Automatically switches to a user-defined "Fixed Ratio" when the ETF is closed.
- Continuous Updates : Prevents values from freezing, calculating a synthetic "Shadow Price" for the closed asset so you can continue to see projected levels based on the live CFD market.
Technical Explanation (The Math)
The indicator functions by calculating a dynamic ratio between the two instruments and using it to convert price levels.
Formulas
1. Calculate Ratio :
Ratio = Price(ETF) / Price(CFD)
2. Conversion :
- ETF Chart → CFD Price :
Equivalent CFD Price = Current ETF Price / Ratio
- CFD Chart → ETF Price :
Equivalent ETF Price = Current CFD Price × Ratio
Example (SPY vs US500)
- Scenario : You are trading on the SPY chart.
- Current Prices :
- SPY (ETF) = $500
- US500 (CFD) = $5000
- Step 1 : Calculate Ratio
- 500 / 5000 = 0.10
- Step 2 : Calculate Equivalent Price
- If SPY moves to $505 , what is the US500 equivalent?
- 505 / 0.10 = 5050
- The indicator will display "US500: 5050" on the label and scale.
Supported Pairs
SPY (AMEX) = US500
GLD (AMEX) = XAUUSD
SLV (AMEX) = XAGUSD
IWM (AMEX) = US2000
QQQ (NASDAQ) = NAS100
IBIT (NASDAQ) = BTCUSD
Settings
- Symbols : Customize the ticker symbols for each pair if your broker uses different names.
- Fixed Ratio (Closed) : Manually adjust the fallback ratio used when the ETF market is closed (default values provided).
- Visuals :
- Toggle Table, Labels, Scale, and Historical Lines on/off.
- Customize colors, text sizes, and positions.
- Right Offset (Bars from Current) : Adjusts how far back (from the current live bar) the Left Virtual Scale is drawn. Increasing this moves the scale further to the left.
- Historical Levels :
- Lookback Length : Number of bars to check for High/Low calculations (Default: 20).
Fixed Risk + Contracts 2.0This is the upgraded version of my Contracts/Risk indicator, released in January 2026. Users will trade responsibly (and never overleverage again!)
1. Pre-Select Your Ticker
MES ES
NQ MNQ
MYM YM
M2K MCL MGC
GC SIL SI
2. Input Current Account Balance and Risk % Each Trade To Grow Your Account
3. Input Stop Amount In Ticks (Use Position Tool for ease)
4. Contract Risk Is Calculated Automatically!
Add to your favourites and comment below if you have any suggestions :)
Herramienta Risk:Reward Pro - MECTRADEROverview: This is an advanced Risk/Reward management tool specifically designed for traders who execute based on Ticks (perfect for Futures like NQ/ES, Gold, or Forex). The main focus of this script is visual clarity and precision.
Key Features:
✅ Clean Visuals (No Dimming): Built using linefill technology with a 92% transparency rate. This ensures the price action remains vibrant and clear. Unlike standard boxes, this tool does not darken or "muddy" the candles when the price enters the zone.
✅ Tick-Based Calculation: Define your Stop Loss and up to 5 Take Profit levels using Ticks for maximum precision.
✅ Toggleable TP Levels: You can enable or disable TP1 through TP5 individually to match your scaling-out strategy.
✅ Dynamic Labels: Automatically displays the level name (Entry, SL, TP) along with the exact price value on the right-side scale.
✅ Long/Short Toggle: Switch between buy and sell setups instantly with a single drop-down selection.
How to use:
Add the script to your chart.
Open Settings and choose your Mode (LONG or SHORT).
Use the Precision Crosshair icon next to "Price Entry" to pick your execution level directly from the chart.
Adjust your Stop Loss and Profit Ticks.
The tool will project your risk zones professionally without interfering with your technical analysis.
Daily DashboardThe Daily Dashboard indicator provides a quick, at-a-glance view of essential daily market statistics directly on your TradingView chart.
Features:
- Daily High & Low: Track the highest and lowest prices of the current trading day.
- Total Daily Volume: Monitor the total trading volume accumulated during the day.
- Previous Day Breakouts: See if today’s price has broken the previous day’s high or low.
- Automatic Updates: All values refresh automatically at the start of a new trading day.
- Pinned Table Layout: Fixed in the top-right corner of the chart for easy reference, independent of price movements.
- Clean Design: White text on a semi-transparent blue background for maximum readability.
Use Cases:
- Day traders needing a quick overview of daily market activity.
- Swing traders monitoring key levels and breakout potential.
- Traders wanting a professional, lightweight dashboard without cluttering the chart.
How It Works:
- Tracks daily high, low, and volume in real time.
- Compares today’s price to the previous day’s high and low to identify breakouts.
- Displays all data neatly in a fixed table pinned to the chart.
Customization:
- Table position is fixed in the top-right corner.
- Background transparency and colors can be adjusted in the script if desired.
Pro Tip:
Combine this dashboard with trend or momentum indicators to create a complete trading setup.
Spectre -Candles Spectre -Candles MEANS SPECTRE CANDLES -
2 candle closing main 2 candle closing main
Session Open/Close Labels - SimpleSimple and Minimal Label that shows Tokyo and EU open and close times on the chart
SPY 200SMA +4% Entry -3% Exit TQQQ/QLD/GLDM THREE PHASE STRATEGYWanted to take a look at all of the individual trades and provide a series of options to balance performance and risk. This post is expanding on my previous one - www.reddit.com
Here is the data and the backtesting splitting the strategy into three primary phases with multiple options and exact trade dates to help people easily backtest other combinations - docs.google.com (Three Tabs with the three phases)
If you just want my personal recommendations this would be what I will be using -
PHASE 1 (Strategy BUY signal triggers when SPY price crosses +4% over the SPY 200SMA) = 100% TQQQ
If trade lasts 366 days (Long Term Cap Gains) go to PHASE 2
If SPY price crosses below -3% SPY 200SMA go to PHASE 3
PHASE 2 (PHASE 1 lasts 366 days) = Deleverage and diversify into 50% QLD & 50% GLDM
PHASE 3 (Strategy SELL signal triggers when SPY price crosses -3% below the SPY 200SMA) = Defensive posture with 50% SGOV & 50% GLDM
As market degrades start selling SGOV and buying QQQ until 50% QQQ & 50% GLDM
TradingView Script for the THREE PHASE STRATEGY (imgur.com):
//
@version=
5
strategy("SPY 200SMA +4% Entry -3% Exit Strategy",
overlay=true,
default_qty_type=strategy.percent_of_equity,
default_qty_value=100)
// === Inputs ===
smaLength = input.int(200, title="SMA Period", minval=1)
entryThreshold = input.float(0.04, title="Entry Threshold (%)", step=0.01)
exitThreshold = input.float(0.03, title="Exit Threshold (%)", step=0.01)
startYear = input.int(1995, "Start Year")
startMonth = input.int(1, "Start Month")
startDay = input.int(1, "Start Day")
// === Time filter ===
startTime = timestamp(startYear, startMonth, startDay, 0, 0)
isAfterStart = time >= startTime
// === Calculations ===
sma200 = ta.sma(close, smaLength)
upperThreshold = sma200 * (1 + entryThreshold)
lowerThreshold = sma200 * (1 - exitThreshold)
// === Strategy Logic ===
enterLong = close > upperThreshold
exitLong = close < lowerThreshold
if isAfterStart
if enterLong and strategy.position_size == 0
strategy.entry("Buy", strategy.long)
if exitLong and strategy.position_size > 0
strategy.close("Buy")
// === 366-Day Marker Logic (Uninterrupted) ===
var
int
targetTime = na
// 1. Capture entry time only when a brand new position starts
if strategy.position_size > 0 and strategy.position_size == 0
targetTime := time + (366 * 24 * 60 * 60 * 1000)
// 2. IMPORTANT: If position is closed or a sell signal hits, reset the timer to "na"
if strategy.position_size == 0
targetTime := na
// 3. Trigger only if we are still in the trade and hit the timestamp
isAnniversary = not na(targetTime) and time >= targetTime and time < targetTime
// === Visuals ===
p_sma = plot(sma200, title="200 SMA", color=color.rgb(255, 0, 242))
p_upper = plot(upperThreshold, title="Entry Threshold (+4%)", color=color.rgb(0, 200, 0))
p_lower = plot(lowerThreshold, title="Exit Threshold (-3%)", color=color.rgb(255, 0, 0))
fill(p_sma, p_upper, color=color.new(color.green, 80), title="Entry Zone")
// Draw marker only if 366 days passed without a sell
if isAnniversary
label.new(bar_index, high, "366 DAYS - PHASE 2", style=label.style_label_down, color=color.yellow, textcolor=color.black, size=size.small)
// === Entry/Exit Labels ===
newOpen = strategy.position_size > 0 and strategy.position_size == 0
newClose = strategy.position_size == 0 and strategy.position_size > 0
if newOpen
label.new(x=bar_index, y=low * 0.97, text="BUY - PHASE 1", xloc=xloc.bar_index, yloc=yloc.price, color=color.lime, style=label.style_label_up, textcolor=color.black, size=size.small)
if newClose
label.new(x=bar_index, y=high * 1.03, text="SELL - PHASE 3", xloc=xloc.bar_index, yloc=yloc.price, color=color.red, style=label.style_label_down, textcolor=color.white, size=size.small)
200 SMA SPY Trading Range Bands Script:
//
@version=
5
indicator("200 SMA SPY Trading Range Bands", overlay=true)
// === Settings ===
smaLength = input.int(200, title="SMA Length")
mult1 = input.float(1.09, title="Multiplier 1 (9% Over)")
mult2 = input.float(1.15, title="Multiplier 2 (15% Over)")
// === Calculations ===
smaValue = ta.sma(close, smaLength)
line9Over = smaValue * mult1
line15Over = smaValue * mult2
// === Plotting ===
plot(smaValue, title="200 SMA", color=color.gray, linewidth=1, style=plot.style_linebr)
plot(line9Over, title="9% Over 200 SMA", color=color.rgb(255, 145, 0), linewidth=1)
plot(line15Over, title="15% Over 200 SMA", color=color.rgb(38, 1, 1), linewidth=2)
Volume Weighted Intra Bar LR KurtosisThis indicator analyzes market character by decomposing total
Excess Kurtosis ("Fat Tails") of a SINGLE BAR into four distinct,
interpretable components based on a Linear Regression model.
Key Features:
1. **Intra-Bar LR Kurtosis Decomposition:** For each bar on the chart,
the indicator analyzes the underlying price action on a smaller
timeframe ('Intra-Bar Timeframe'). It fits a Linear Regression
line through the intra-bar data to decompose the 4th Moment:
- **Trend Kurtosis (Gold):** Peakedness of the regression line
itself. High values indicate the price path within the bar
moves in sudden jumps, steps, or gaps (discontinuous path).
- **Residual Kurtosis (Red):** Excess Kurtosis of the noise
around the regression line. Captures "Hidden Tail Risk" or
extreme outliers within the bar relative to the trend.
- **Within-Bar Kurtosis (Blue):** Fat tails derived from the
microstructure of individual intra-bar candles.
- **Interaction Variance (Dark Grey):** The comovement of variance
and mean deviations (volatility clustering relative to trend).
- **Interaction Skewness (Darker Grey):** The comovement of skewness
and mean deviations (asymmetry relative to trend).
2. **Visual Decomposition Logic:** Total Excess Kurtosis is the
primary metric displayed. Since statistical moments are additive,
this indicator calculates the *exact* Total Kurtosis and partitions
the columns based on the Law of Total Moments.
3. **Dual Display Modes:** The indicator offers two modes to
visualize this decomposition:
- **Absolute Mode:** Plots the *total* kurtosis as a
stacked column chart. Stacking logic groups components to
ensure visual clarity of the magnitude.
- **Relative Mode:** Plots the direct *contribution ratio*
(proportion) of each component relative to the total sum,
ideal for identifying the dominant driver (Trend vs. Noise).
4. **Calculation Options:**
- **Normalization:** An optional 'Normalize' setting
transforms inputs into logarithmic space, analyzing the
kurtosis of *returns* rather than absolute prices.
- **Volume Weighting:** An option (`Volume weighted`) applies
volume weighting to all regression and moment calculations,
emphasizing high-participation moves.
5. **Kurtosis Cycle Analysis:**
- **Pivot Detection:** Includes a built-in pivot detector
that identifies significant turning points (peaks/valleys) in
the *total* kurtosis line. (Note: This is only visible
in 'Absolute Mode').
- **Flexible Pivot Algorithms:** Supports various underlying
mathematical models for pivot detection provided by the
core library.
6. **Note on Confirmation (Lag):** Pivot signals are confirmed
using a lookback method. A pivot is only plotted *after*
the `Pivot Right Bars` input has passed, which introduces
an inherent lag.
7. **Multi-Timeframe (MTF) Capability:**
- **MTF Analysis Lines:** The entire intra-bar analysis can be
run on a higher timeframe (using the `Timeframe` input),
with standard options to handle gaps (`Fill Gaps`) and
prevent repainting (`Wait for...`).
- **Limitation:** The Pivot detection (`Calculate Pivots`) is
**disabled** if a Higher Timeframe (HTF) is selected.
8. **Integrated Alerts:** Includes comprehensive alerts for:
- Kurtosis magnitude (High Positive / High Negative).
- Character changes (Trend Jumps vs. Noise Outliers).
- Total Kurtosis pivot (High/Low) detection.
**Caution: Real-Time Data Behavior (Intra-Bar Repainting)**
This indicator uses high-resolution intra-bar data. As a result, the
values on the **current, unclosed bar** (the real-time bar) will
update dynamically as new intra-bar data arrives. This behavior is
normal and necessary for this type of analysis. Signals should only
be considered final **after the main chart bar has closed.**
---
**DISCLAIMER**
1. **For Informational/Educational Use Only:** This indicator is
provided for informational and educational purposes only. It does
not constitute financial, investment, or trading advice, nor is
it a recommendation to buy or sell any asset.
2. **Use at Your Own Risk:** All trading decisions you make based on
the information or signals generated by this indicator are made
solely at your own risk.
3. **No Guarantee of Performance:** Past performance is not an
indicator of future results. The author makes no guarantee
regarding the accuracy of the signals or future profitability.
4. **No Liability:** The author shall not be held liable for any
financial losses or damages incurred directly or indirectly from
the use of this indicator.
5. **Signals Are Not Recommendations:** The alerts and visual signals
(e.g., crossovers) generated by this tool are not direct
recommendations to buy or sell. They are technical observations
for your own analysis and consideration.






















