Midnight Open Retracement [LuxAlgo]The Midnight Open Retracement indicator highlights the 12:00 AM ET opening price and provides real-time probability statistics for price retracing to this level during the New York session.
Designed specifically with NQ (Nasdaq 100) futures data in mind, the tool helps traders identify high-probability "magnet" levels for New York open scalps based on historical performance.
🔶 USAGE
The Midnight Open is a cornerstone of ICT concepts, acting as a "true" daily open that often serves as a point of institutional re-accumulation or distribution. This script automates the identification of this level and provides a dashboard to help traders decide when to expect a retracement.
🔹 Identifying the Bias
The script compares the New York opening price (9:30 AM ET) to the Midnight opening price:
If NY opens above the Midnight Open, the indicator identifies a potential bearish retracement bias toward the level. If NY opens below the Midnight Open, the indicator identifies a potential bullish retracement bias toward the level.
🔹 Using as a Profit Target
Because the Midnight Open is retraced to frequently, it serves as an ideal Take Profit (TP) target for opening range scalps. The indicator marks the exact moment a retracement occurs with a visual marker, confirming the level has been tested.
🔶 DETAILS
The statistics integrated into this tool are based on extensive backtesting of NQ futures over 6-month periods. Understanding these probabilities allows traders to filter out low-conviction setups and focus on high-probability days.
🔹 The Core Probabilities
When price opens above the midnight level, it retraces to touch it 74% of the time. When price opens below the midnight level, it retraces to touch it 63% of the time.
🔹 Weekday Variance
Not all trading days are equal. The script accounts for "By Weekday" statistics:
High Probability (Wednesdays): On Wednesdays, retracement probabilities can jump as high as 89% for opens above the midnight level. Low Probability (Mondays): Mondays often exhibit "Avoid" criteria, with retracement probabilities frequently falling below 60%.
The dashboard dynamically updates the "Probability of Retracement" based on the current day of the week, helping you stay aligned with historical data.
🔶 SETTINGS
🔹 Session Settings
Timezone Mode: Choose between Exchange time or "America/New_York" (recommended for ICT concepts). Midnight Open Time: The specific time used to set the daily baseline. NY Open Time: The time used to determine the session opening bias. NY Session Range: Defines the boundary for the New York session box.
🔹 Visual Settings
Show Midnight Level: Toggles the horizontal line representing the midnight price. Show Retrace Circle: Displays markers on the chart when the retracement goal is met. Show NY Session Box: Draws a dynamic box for the NY session that changes color based on the current price relative to the open.
🔹 Dashboard Settings
Show Insights Report: Toggles the statistics dashboard on the chart. Position/Size: Controls the UI placement and scale of the data table.
Chỉ báo và chiến lược
Dynamic Trend-Based Fibonacci Extension💡 This indicator is a sophisticated, automated technical analysis tool designed to identify high-probability trend continuation setups using the principles of market structure and Fibonacci geometry. By algorithmically detecting "A-B-C" price structures (Pivot -> Impulse -> Retracement), it projects dynamic Fibonacci Extension levels to forecast potential price targets for the next impulsive move (Wave C to D). Unlike static drawing tools, this script adapts to market volatility and features an advanced invalidation engine to keep your charts clean and your risk managed.
✨ Originality and Utility
Traders often struggle with the subjectivity of drawing Fibonacci extensions manually. This script solves that by standardizing the identification of market structure using a proprietary ZigZag algorithm enhanced with Average True Range (ATR) for volatility-adjusted sensitivity.
Key unique features include:
Automated Structure Detection: Instantly spots Bullish (Higher High, Higher Low) and Bearish (Lower Low, Lower High) sequences without manual input.
Dynamic Invalidation: The script monitors price action in real-time. If price breaks the invalidation point (Point A), the structure is immediately "grayed out" or deleted, preventing you from trading based on broken setups.
Golden Zone Targeting: Highlights the high-probability reversal zone between the 1.5 and 1.618 extensions, often associated with the completion of a measured move.
JSON Alerting: Built-in support for algorithmic trading with structured JSON payloads (Entry, TP, SL) ready for webhook integration.
🔬 Methodology and Concepts
The core logic operates on a three-step algorithmic sequence:
1. Pivot Identification: The script uses a "ZigZag" approach to find significant swing highs and lows. It employs an ATR-based threshold (or fixed deviation) to filter out market noise, ensuring only significant structural points are considered.
2. Geometric Validation: It evaluates the last three pivot points (A, B, C) to confirm a valid trend structure.
Bullish Setup: Point C must be higher than Point A but lower than Point B (a valid retracement).
Bearish Setup: Point C must be lower than Point A but higher than Point B.
3. Projection Mathematics: Once a valid ABC structure is locked, the script calculates extension targets using the standard formula: Target = Price C + ((Price B - Price A) * Ratio) . It also supports Logarithmic Scale calculations for assets with exponential growth, such as cryptocurrencies, ensuring proportional accuracy over large price ranges.
🎨 Visual Guide
The indicator paints a clear, detailed roadmap on your chart. Here is how to interpret the visual elements:
● Structure Lines
Solid Line (A to B): Represents the initial "Impulse" leg of the move.
Dashed Line (B to C): Represents the "Retracement" or corrective leg.
Green Structures: Indicate Bullish setups (looking for long entries).
Red Structures: Indicate Bearish setups (looking for short entries).
Gray/Dimmed Structures: These are invalidated setups where the price has breached the Stop Loss level (Point A).
● Extension Levels (Targets)
The script projects the following key Fibonacci ratios extending from Point C:
0.618 (Wave 5): An early profit-taking level, often corresponding to a truncated 5th wave.
1.0 (Measured Move): Where the extension equals the length of the initial impulse (AB = CD pattern).
1.272 (Harmonic): A common extension level for corrective structures or deep pullbacks.
Golden Zone (1.5 - 1.618): A highlighted fill area. The 1.618 level (Solid Line) is the "Golden Ratio" and is statistically one of the most significant targets in trending markets, often labeled as "Wave 3".
● Labels
Points A, B, C: Clearly marks the swing points defining the structure.
Right-Side Labels: Display the Ratio (e.g., 1.618) and the exact Price Level for easy order placement.
📖 How to Use
This tool is best used as a trend-following system.
1. Trend Identification
Wait for a new Solid Colored Structure (Green or Red) to appear. This confirms that a valid ABC retracement has occurred.
2. Entry Strategy
The "Trigger" is generally the reversal from Point C. Aggressive traders enter near C, while conservative traders may wait for a breakout above B.
Stop Loss: Place your SL just beyond Point A . If price breaks A, the script will automatically gray out the structure, signaling invalidation.
3. Profit Taking
Use the projected extension lines as dynamic Take Profit (TP) zones:
TP1: 1.0 (The Measured Move).
TP2: The Golden Zone (1.5 to 1.618). This is often the strongest target for a Wave 3 impulsive move.
4. Automation
For automated traders, create an alert using the "Any alert() function call" option. The script outputs a JSON string containing the Action, Ticker, Entry Price, TP (1.618), and SL (Point A).
⚙️ Inputs and Settings
You can fully customize the script to fit your asset class and timeframe:
● ZigZag Detection
Pivot Lookback Depth: (Default: 5) Determines how many bars to check left/right for a pivot. Higher numbers find larger, more significant structures.
Use ATR-Based Threshold: (Default: True) Adapts the sensitivity to market volatility.
ATR Multiplier: (Default: 2.0) Adjusts how much price must reverse to form a new leg.
● Structure Invalidation
Enable Structure Invalidation: (Default: True) Toggles the logic that checks if Point A is breached.
Invalidation Action: Choose "Gray Out" to keep history visible but dimmed, or "Delete" to remove failed setups entirely.
● Fibonacci Settings
Use Logarithmic Scale: Essential for crypto or long-term timeframe analysis.
Show 0.618 / 1.0 / 1.272 / 1.618: Toggles individual levels on/off to declutter the chart.
Extend Lines Right: Extends the target lines into the future for better visibility.
● Display Settings
Keep Last N Structures: Controls how many historical structures remain on the chart to prevent visual clutter.
Show Elliott Wave Labels: Adds theoretical wave counts (e.g., "Wave 3") to the ratio labels.
🔍 Deconstruction of the Underlying Scientific and Academic Framework
This indicator is grounded in Fractal Market Geometry and Elliott Wave Theory .
1. The Golden Ratio (Phi - 1.618):
Mathematically derived from the Fibonacci sequence, the 1.618 ratio is omnipresent in natural growth patterns. In financial markets, it represents the psychological "tipping point" of crowd behavior during an impulsive trend. This script emphasizes the 1.618 extension as the primary target for a "Wave 3," which is academically cited as typically the longest and strongest wave in a 5-wave motive sequence.
2. Harmonic AB=CD Patterns:
The inclusion of the 1.0 extension validates the "Measured Move" concept. Statistically, markets often move in symmetrical legs where the secondary impulse (CD) equals the magnitude of the primary impulse (AB).
3. Volatility Normalization (ATR):
By utilizing the Average True Range (ATR) for pivot detection, the script adheres to statistical volatility normalization. This ensures that the structures identified are statistically significant relative to the asset's current volatility regime, rather than relying on arbitrary percentage moves which fail across different asset classes.
⚠️ Disclaimer
All provided scripts and indicators are strictly for educational exploration and must not be interpreted as financial advice or a recommendation to execute trades. I expressly disclaim all liability for any financial losses or damages that may result, directly or indirectly, from the reliance on or application of these tools. Market participation carries inherent risk where past performance never guarantees future returns, leaving all investment decisions and due diligence solely at your own discretion.
Sai & Deb DMISai & Deb DMI with horizontal lines. Existing DMI lines are used and various levels can be drawn between 0 and 100 to see the trend reversals.
Wick Statistics (Intra-Day)Data box that shows smallest, largest, and average wick point size during specified time ranges.
Candle Type Analyzerthis indicator identifies the different types of candle which are divided into 4 four types
1.marubozu candle
2.normal candle
3.pinbar/doji candle
4.special marubozu candle
1.maru candle - having body >70% of total length
2.normal candle - having body >=30% and <=70% of total length
3.pinbar/doji candle - having body <30% of total length
4.special marubozu candle - a.green candle - closing within top 10% of total length
b.red candle - closing within bottom 10% of total length
total length of a candle = measured from high to low of the candle
you can give labels for each candle type on top of the candle
1.marubozu candle - M
2.normal candle - N
3.pinbar/doji candle - P
4.special marubozu candle - S
try making the colour of labels with one colour only for better and faster coordination with the mind
EMA Core Bounce FX (MTF safe Daily Logic)Daily chart core bounce strat
tested works well with the ! H version
CANDLE STRUCTURE FILTER PRO by HeruprastCandle Structure Filter
CANDLE STRUCTURE FILTER PRO is a price-action-based indicator that filters trading signals using candle body strength, wick ratio, and EMA trend alignment. It only generates non-repainting BUY/SELL signals on strong candles with valid structure, aligned with the selected trend EMA, and confirmed by an EMA Gap Filter to avoid sideways or choppy market conditions.
Designed for scalping to intraday trading, especially effective on volatile instruments like XAUUSD, with automatic calibration based on timeframe and instrument characteristics.
Liquidity Sweep Strategy (RR 1:2)This free indicator from its strategic department has a 60% profit target of 2% and a loss target of 1%.
Buy LineBuy Line based on volatility at highest close in period and an additional configurable multiplier on top
ZenAlgo - GridOverview and anchoring logic
This indicator constructs a price grid based on a dynamically or manually defined price swing. The entire calculation starts by defining two anchor points that represent a completed directional move. These anchors can be selected in two ways:
Manually, by specifying a start time and an end time, where the indicator uses the candle corresponding to those times and selects either wick highs or lows depending on direction.
Automatically, by detecting significant swing points derived from recent price extremes over a configurable historical window.
The chosen anchors form a reference segment between point A and point B. This segment defines both direction and magnitude of the move. All subsequent levels and zones are derived relative to this segment, ensuring the grid adapts to current market structure rather than using fixed price distances.
Difference from traditional grid and Fibonacci tools
Unlike fixed price grids or standard Fibonacci tools that require manual anchoring and remain static once drawn, this indicator continuously derives its grid from the most relevant completed price swing. Instead of treating levels as independent horizontal prices, all values are expressed as proportions of a single measured move, allowing the grid to automatically rescale and realign as market structure evolves.
Market structure detection and directional context
Before the grid itself is drawn, the script continuously evaluates price structure using swing detection over two different sensitivities. Larger swings establish the dominant structural direction, while smaller swings can optionally be shown for internal context.
Swing highs and swing lows are detected by comparing historical highs and lows over a rolling window.
When price crosses above or below the most recent structural level, the script classifies the event as either a continuation in the same direction or a change in direction.
This structural state determines whether the grid is treated as upward or downward and influences the visual orientation of labels and zones.
This step matters because retracement and extension levels only have meaning when referenced to a clearly defined directional move.
Primary range construction between anchors
Once the anchor points are established, the indicator measures the vertical price distance between them. This distance is treated as a normalized range rather than an absolute value. Every level drawn afterward is positioned as a proportional offset of this range.
If the second anchor is above the first, the grid is considered bullish.
If the second anchor is below the first, the grid is considered bearish.
Colors and label orientation adapt automatically to this direction.
By normalizing the range, the grid remains comparable across assets and timeframes.
Retracement and extension level placement
The indicator plots a predefined set of proportional levels between and beyond the anchor points. Each level represents a fraction or multiple of the original move.
Lower values correspond to deeper retracements toward the origin of the move.
Mid-range values represent partial pullbacks within the move.
Higher values extend beyond the move, projecting potential continuation zones.
Each level is drawn as a horizontal line extending into future bars, accompanied by a label. Labels can be shown either as descriptive names or as raw proportional values, depending on user preference.
Zone construction instead of single levels
Rather than relying only on precise price lines, the indicator groups selected proportions into zones. This reflects the observation that price interaction typically occurs across ranges rather than at exact prices.
A retracement zone highlights an area between two closely spaced proportional levels.
A projection zone marks a continuation region beyond the measured move.
These zones are drawn as shaded areas extending forward in time.
Visual reference points
The indicator explicitly marks the two anchor points on the chart.
Point A represents the origin of the measured move.
Point B represents the completion of that move.
This allows the user to visually verify which price swing the grid is derived from.
How to interpret the values
All plotted levels express proportional relationships to the measured move, not independent price predictions.
Lower proportional values indicate proximity to the start of the move.
Mid-range values represent partial retracements.
Higher values indicate projected continuation areas.
How to best use this indicator
This indicator serves as a structural reference tool rather than a signal generator.
Apply it after a clear directional swing has formed.
Use higher-timeframe context to validate anchor selection.
Combine the grid with price behavior and other contextual tools.
Limitations and disclaimers
This indicator is purely proportional and structure-based.
It does not incorporate volume, volatility regimes, or fundamental data.
Automatic anchoring may differ from subjective swing selection.
Levels and zones represent reference areas, not guaranteed reaction points.
The indicator describes price structure and proportional relationships only.
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.
Double Bollinger Bands Strategy_investalotDual Bollinger Band Swing Trading System Indicator Setup
• Bollinger Band 1: Period 20, Deviation 2
• Bollinger Band 2: Period 20, Deviation 0.7
• Timeframe: Daily (Primary)
• Markets: NSE Equity – Liquid Large & Mid Caps
Market Conditions
• 20 SMA must slope upward for long trades • Price must hold above 200 DMA
• Avoid flat or sideways markets
Buy Setup – Trend Continuation
1. Strong impulse move into upper BB (20,2)
2. Pullback into zone between BB (20,0.7) and 20 SMA 3. Bullish candle confirmation inside value zone
Entry Rules
• Buy above bullish confirmation candle high
• Volume should be at least average or higher
Stop Loss Rules
• Initial SL below 20 SMA
• Aggressive SL below BB (20,0.7) lower
Targets & Exit
• Target 1: Upper BB (20,0.7)
• Target 2: Upper BB (20,2)
• Trail SL to 20 SMA once price enters momentum zone
Risk Management
• Risk per trade: 0.5% – 1% of capital
• Maximum 3 open swing trades at a time
Trade Avoidance Rules
• Avoid earnings weeks
• Avoid low volume stocks
• Avoid trades when price remains inside BB (20,0.7)
Spectre -Candles Spectre -Candles MEANS SPECTRE CANDLES -
2 candle closing main 2 candle closing main
High&Low - Scalping🔹 High and Low Scalping – Key Levels Indicator 🔹
High and Low Scalping is an indicator designed for active traders and scalpers who want to instantly identify the most important price levels in the market.
The indicator automatically plots:
📈 The monthly high and low
📊 The previous week's high and low (weekly)
⏱️ The previous day's high and low (daily)
These levels are recognized as major liquidity zones, which are often respected by the price and used by institutions.
⚙️ Main features
✔️ 100% automatic update
✔️ No manual calculations required
✔️ Clear and quick reading of the market
✔️ Compatible with scalping, day trading, and intraday trading
🎯 Why use High and Low Scalping?
Identify price reaction zones
Spot precise scalping opportunities
Improve entry and exit timing
Trade with a clean and objective market structure
This indicator is an essential tool for any trader who wants to rely on reliable, simple, and effective technical levels without overloading their chart.
FVG Detector - With Close Direction & Breakoutgreat. now, after the touching candle the ones that obeyed the last command with zero balls, indicate when the next candle, ie the candle following the ones with yellow and green balls, trades above the high of the yellow balls candle and vice versa. ie for yellow balls(candles that trade up to touch the fvg), the next candle after it will have to trade above the high of the touching yellow candle. and vice versa for the green one
Portfolio Table v5 This lightweight and functional tool allows traders to track multiple stock positions directly on their chart in a clean, organized table. Specifically designed with the Tel Aviv Stock Exchange (TASE) in mind, it includes a built-in toggle to handle price conversions between Agorot and NIS.
HTT Range BreakoutTime range breakout with targets.
If breakout bottom line is stoploss
if breakdown top line is stoploss
Sequential - Heatmap [R2D2]The Professional Edge in Trend Exhaustion
In a market environment saturated with noise, the most valuable tool for a trader is clarity. Standard trend-following indicators often lag, and traditional reversal markers can be premature. The Sequential: Heatmap is a sophisticated trend-exhaustion indicator designed to identify precise market inflection points where a trend has reached its mathematical limit.
By focusing on the Exhaustion Phase (counts 7, 8, and 9) and integrating Perfection Logic, this tool filters out "weak" setups, highlighting only the high-probability price flips that professional institutional traders watch.
How It Works: The Logic of Exhaustion
The Sequential operates on the principle of price symmetry. A "Setup" occurs when a series of at least nine consecutive bars close higher (for a Sell Setup) or lower (for a Buy Setup) than the close of the bar four periods prior.
The "Perfected" Difference
A standard 9-count is often not enough for a high-conviction entry. This publication-ready script includes Perfection Logic:
Perfected Buy (9★) : The low of bar 8 or 9 must be lower than the lows of both bars 6 and 7.
Perfected Sell (9★) : The high of bar 8 or 9 must be higher than the highs of both bars 6 and 7.
This ensures that the final move in the sequence is a true "climax" before the reversal begins.
Step-by-Step Usage Guide
Step 1: Monitor the Heatmap
As a trend develops, the bars will remain standard. Once the sequence hits count 7, the Heatmap Gradient activates.
Faint Color: Momentum is beginning to stretch.
Deep Saturated Color: The trend is entering the danger zone for a reversal.
Step 2: Identify the 9★ Completion
Wait for the number 9 to appear. If a star (★) is attached, the setup is "Perfected". This is your primary signal that the current move is mathematically overextended.
Step 3: Define Your Risk with Risk Lines
Upon completion of a 9-count, the script draws a solid thin horizontal line:
Green Line (Resistance) : The ceiling of the move. Use this as a profit target for longs or a hard stop for shorts.
Red Line (Support) : The floor of the move. Use this as a profit target for shorts or a hard stop for longs.
Trading Like a Pro: Strategies for Success
To use this tool effectively at a professional level, follow these three core tenets:
Don’t Front-Run the 9 : Amateur traders often try to "guess" the reversal at count 5 or 6. Professionals wait for the Perfected 9 to close. The heatmap is designed to keep you patient.
The "Risk Line" Breaker : If price closes beyond a Risk Line (e.g., closes above the green resistance line), the exhaustion has failed, and a "Setup Trend Extension" is occurring. In this case, exit your reversal trade immediately; the trend is stronger than the exhaustion.
Confluence with Higher Timeframes : A Perfected 9 on a 15-minute chart is strong; a Perfected 9 on a 15-minute chart that aligns with a 4-hour Risk Line is institutional grade.
Advanced Strategy Template This script is a strategy execution and risk-management template designed to test external indicators under consistent and repeatable conditions.
The script does not generate buy or sell signals internally. All trade entries and exits are driven by a user-supplied indicator through a numeric connector. This design intentionally separates signal generation from trade execution, allowing users to evaluate indicators without rewriting strategy logic.
Purpose and Originality
The purpose of this template is to provide a standardized execution framework rather than a trading methodology.
Instead of embedding a specific signal logic, the script focuses on how trades are managed after a signal occurs. This allows users to:
Benchmark different indicators under identical execution rules
Compare stop-loss and take-profit models objectively
Study the impact of risk constraints on performance
Reduce bias caused by inconsistent trade management
This makes the script suitable for educational testing and experimentation, not for presenting a profitable strategy.
How the Signal Connector Works
The strategy listens to a single numeric data source supplied by an external indicator.
The indicator must output values using the following convention:
1 → open long position
-1 → open short position
0 → no action
Optional:
2 → custom close for long
-2 → custom close for short
The strategy reacts only to these values and ignores all other indicator logic.
Example Connector Code (Indicator Side)
Users must add the following logic to their indicator to make it compatible with this template:
// Strategy Connector
// 1 = Buy
// -1 = Sell
// 0 = No Signal
signal = buySignal ? 1 : sellSignal ? -1 : 0
plot(signal, title="Connector", display=display.none)
buySignal and sellSignal represent the indicator’s own conditions
The connector plot is hidden and used only as a data source
How to Connect the Indicator to the Strategy
Add the indicator (with connector output) to the chart
Add this strategy template to the same chart
Open the strategy’s settings
Set Data source to the indicator’s Connector plot
Configure risk, stop-loss, and take-profit settings as required
The strategy will not execute trades unless a valid connector signal is received.
Execution and Risk-Management Features
This template provides configurable execution modules including:
Position sizing and pyramiding control
Maximum drawdown and intraday loss limits
Consecutive win, loss, and losing-day limits
Stop-loss methods (percent, trailing, ATR, structure-based)
Take-profit models (single target, tiered targets, risk-reward, Fibonacci levels)
Optional breakeven logic
Session-based trading control
All execution logic operates independently of the signal source.
Strategy Properties and Results
Default strategy properties are intentionally conservative and provided only as a demonstration baseline.
Backtest results depend entirely on:
The connected indicator
Market and timeframe selection
User-defined execution parameters
Results shown by this template do not represent a trading edge and should not be interpreted as investment advice.
Intended Use
This script is intended for:
Educational study of trade execution and risk control
Indicator benchmarking under identical execution rules
Exploring how exits and risk constraints influence outcomes
It is not intended to promote or present a standalone trading strategy.
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.






















