Wheel Strategy SMAsPlots the 200 SMA and 50 SMA- For CSP, look for a strike price that is at or just below teh 200 sma
指標和策略
CK Auto Adaptive StoplossThis tool automatically finds the best stop-loss for every trade by analyzing candle structure, ATR volatility, volume spikes, and market momentum. It tightens or widens the stop dynamically and shows you exactly how many contracts you can use based on your risk per trade.
It also plots bold stop-loss lines on your chart and includes a live position-sizing table so you always stay consistent.
Reversal (Heikin Ashi-ready)This indicator detects bullish and bearish reversal patterns based purely on price action relative to prior candles. It is designed to be Heikin Ashi–compatible, meaning it can optionally use HA OHLC values rather than standard candles.
The script identifies:
Bullish reversals (V Up triangles)
Bearish reversals (V Down triangles)
It uses a two-stage system:
Context detection (a potential reversal setup forms).
Confirmation detection (price breaks a key level within a specified number of bars).
SPX Expected High/Low Move, S&R, Gamma (Daily Manual update Req)This script enables users to manually plot the anticipated low and high price movements, while also visualizing both positive and negative gamma exposures. The anticipated low represents the projected downside threshold based on expected volatility, whereas the anticipated high reflects the potential upside boundary under similar conditions. Positive gamma indicates scenarios where option positions benefit from underlying price movements, enhancing convexity and reducing directional risk. Conversely, negative gamma highlights exposures where option positions lose value as the underlying price moves, amplifying directional risk and requiring active hedging.
I use Barchart to manually update my personal chart each morning. I am not responsible for any information presented on their website. This is a reference tool to determine when and where to take profit, levels where price will test, etc. Use in conjunction with the appropriate EMAs for your timeframe and strategy.
S&D Light+ Enhanced# S&D Light+ Enhanced - Supply & Demand Zone Trading Strategy
## 📊 Overview
**S&D Light+ Enhanced** is an advanced Supply and Demand zone identification and trading strategy that combines institutional order flow concepts with smart money techniques. This strategy automatically identifies high-probability reversal zones based on Break of Structure (BOS), momentum analysis, and first retest principles.
## 🎯 Key Features
### Smart Zone Detection
- **Automatic Supply & Demand Zone Identification** - Detects institutional zones where price is likely to react
- **Multi-Candle Momentum Analysis** - Validates zones with configurable momentum requirements
- **Break of Structure (BOS) Confirmation** - Ensures zones are created only after significant structure breaks
- **Quality Filters** - Minimum zone size and ATR-based filtering to eliminate weak zones
### Advanced Zone Management
- **Customizable Zone Display** - Choose between Geometric or Volume-Weighted midlines
- **First Retest Logic** - Option to trade only the first touch of each zone for higher probability setups
- **Zone Capacity Control** - Maintains a clean chart by limiting stored zones per type
- **Visual Zone Status** - Automatically marks consumed zones with faded midlines
### Risk Management
- **Dynamic Stop Loss** - Positioned beyond zone boundaries with adjustable buffer
- **Risk-Reward Ratio Control** - Customizable R:R for consistent risk management
- **Entry Spacing** - Minimum bars between signals prevents overtrading
- **Position Sizing** - Built-in percentage of equity allocation
## 🔧 How It Works
### Zone Creation Logic
**Supply Zones (Selling Pressure):**
1. Strong momentum downward movement (configurable body-to-range ratio)
2. Identified bullish base candle (where institutions accumulated shorts)
3. Break of Structure downward (price breaks below recent swing low)
4. Zone created at the base candle's high/low range
**Demand Zones (Buying Pressure):**
1. Strong momentum upward movement
2. Identified bearish base candle (where institutions accumulated longs)
3. Break of Structure upward (price breaks above recent swing high)
4. Zone created at the base candle's high/low range
### Entry Conditions
**Long Entry:**
- Price retests a demand zone (touches top of zone)
- Rejection confirmed (close above zone)
- Zone hasn't been used (if "first retest only" enabled)
- Minimum bars since last entry respected
**Short Entry:**
- Price retests a supply zone (touches bottom of zone)
- Rejection confirmed (close below zone)
- Zone hasn't been used (if "first retest only" enabled)
- Minimum bars since last entry respected
## ⚙️ Customizable Parameters
### Display Settings
- **Show Zones** - Toggle zone visualization on/off
- **Max Stored Zones** - Control number of active zones (1-50 per type)
- **Color Customization** - Adjust supply/demand colors and transparency
### Zone Quality Filters
- **Momentum Body Fraction** - Minimum body size for momentum candles (0.1-0.9)
- **Min Momentum Candles** - Number of consecutive momentum candles required (1-5)
- **Big Candle Body Fraction** - Alternative single-candle momentum threshold (0.5-0.95)
- **Min Zone Size %** - Minimum zone height as percentage of price (0.01-5.0%)
### BOS Configuration
- **Swing Length** - Lookback period for structure identification (3-20)
- **ATR Length** - Period for volatility measurement (1-50)
- **BOS Required Break** - ATR multiplier for valid structure break (0.1-3.0)
### Midline Options
- **None** - No midline displayed
- **Geometric** - Simple average of zone top/bottom
- **CenterVolume** - Volume-weighted center based on highest volume bar in window
### Risk Management
- **SL Buffer %** - Additional space beyond zone boundary (0-5%)
- **Take Profit RR** - Risk-reward ratio for target placement (0.5-10x)
### Entry Rules
- **Only 1st Retest per Zone** - Trade zones only once for higher quality
- **Min Bars Between Entries** - Prevent overtrading (1-20 bars)
## 📈 Recommended Settings
### Conservative (Lower Frequency, Higher Quality)
```
Momentum Body Fraction: 0.30
Min Momentum Candles: 2-3
BOS Required Break: 0.8-1.0
Min Zone Size: 0.15-0.20%
Only 1st Retest: Enabled
```
### Balanced (Default)
```
Momentum Body Fraction: 0.28
Min Momentum Candles: 2
BOS Required Break: 0.7
Min Zone Size: 0.12%
Only 1st Retest: Enabled
```
### Aggressive (Higher Frequency, More Signals)
```
Momentum Body Fraction: 0.20-0.25
Min Momentum Candles: 1-2
BOS Required Break: 0.4-0.5
Min Zone Size: 0.08-0.10%
Only 1st Retest: Disabled
```
## 🎨 Visual Elements
- **Red Boxes** - Supply zones (potential selling areas)
- **Green Boxes** - Demand zones (potential buying areas)
- **Dotted Midlines** - Center of each zone (fades when zone is used)
- **Debug Triangles** - Shows when zone creation conditions are met
- Red triangle down = Supply zone created
- Green triangle up = Demand zone created
## 📊 Best Practices
1. **Use on Higher Timeframes** - 1H, 4H, and Daily charts work best for institutional zones
2. **Combine with Trend** - Trade zones in direction of overall market structure
3. **Wait for Confirmation** - Don't enter immediately at zone touch; wait for rejection
4. **Adjust for Market Volatility** - Increase BOS multiplier in choppy markets
5. **Monitor Zone Quality** - Fresh zones typically have higher success rates
6. **Backtest Your Settings** - Optimize parameters for your specific market and timeframe
## ⚠️ Risk Disclaimer
This strategy is for educational and informational purposes only. Past performance does not guarantee future results. Always:
- Use proper position sizing
- Set appropriate stop losses
- Test thoroughly before live trading
- Consider market conditions and overall trend
- Never risk more than you can afford to lose
## 🔍 Data Window Information
The strategy provides real-time metrics visible in the data window:
- Supply Zones Count
- Demand Zones Count
- ATR Value
- Momentum Signals (Up/Down)
- BOS Signals (Up/Down)
## 📝 Version History
**v1.0 - Enhanced Edition**
- Improved BOS detection logic
- Extended base candle search range
- Added comprehensive input validation
- Enhanced visual feedback system
- Robust array bounds checking
- Debug signals for troubleshooting
## 💡 Tips for Optimization
- **Trending Markets**: Lower momentum requirements, tighter BOS filters
- **Ranging Markets**: Increase zone size minimum, enable first retest only
- **Volatile Assets**: Increase ATR multiplier and SL buffer
- **Lower Timeframes**: Reduce swing length, increase min bars between entries
- **Higher Timeframes**: Increase swing length, relax momentum requirements
---
**Created with focus on institutional order flow, smart money concepts, and practical risk management.**
*Happy Trading! 📈*
Indicator ***TuYa*** V8.2 – HH/HL MTF + Peak Mid ZoneIndicator TuYa V8.0 – HH/HL MTF + Peak Mid Zone
TuYa V8.0 combines multi-timeframe market structure with a Peak Reaction midline to create clean, rule-based reversal and trend entries – designed primarily for 1-minute execution with 1-hour bias.
🧠 Core Concept
This indicator fuses three ideas:
HTF Peak Reaction Midline (1H)
Uses a Peak Reaction style logic on the higher timeframe (HTF, default: 1H).
Identifies a reaction high and reaction low, then calculates their midpoint → the Peak Mid Zone.
This midline acts as a dynamic sentiment divider (above = premium / below = discount).
Multi-Timeframe HH/HL/LH/LL Structure
HTF structure (1H): detects HH, HL, LH, LL using pivot highs/lows.
LTF structure (1m): detects HH, HL, LH, LL on the execution timeframe (chart TF, intended for 1m).
HTF → LTF Confirmation Window
After a 1H structure event (HH, HL, LL, LH), the indicator opens a confirmation window of up to N LTF candles (default: 10 x 1m bars).
Within that window, the required 1m structure event must occur to confirm an entry.
🎯 Signal Logic
All entries are generated on the LTF (e.g. 1m chart), using HTF (e.g. 1H) bias + Peak Mid Zone:
1️⃣ Price ABOVE Peak Mid (Bullish premium zone)
Reversal SELL
HTF: HH (Higher High)
Within N 1m bars: LTF HH
→ SELL signal (fading HTF strength near premium)
Trend/Bullish BUY
HTF: HL (Higher Low)
Within N 1m bars: LTF LL
→ BUY signal (buying dips in an uptrend above midline)
2️⃣ Price BELOW Peak Mid (Bearish discount zone)
Reversal BUY
HTF: LL (Lower Low)
Within N 1m bars: LTF LL
→ BUY signal (catching potential reversal from discount)
Trend/Bearish SELL
HTF: LH (Lower High)
Within N 1m bars: LTF HH
→ SELL signal (shorting strength in a downtrend below midline)
Signals are plotted as small BUY/SELL triangles on the chart and exposed via alert conditions.
🧾 Filters & Options
⏳ HTF → LTF Delay Window
Input: “Max 1m bars after HTF trigger” (default: 10)
After a 1H HH/HL/LL/LH event, the indicator waits up to N LTF candles for the matching 1m structure pattern.
If no match occurs within the window, no signal is generated.
📉 RSI No-Trade Zone (HTF)
Toggle: Use RSI no-trade zone
Inputs:
RSI Length (HTF)
No-trade lower bound (default 45)
No-trade upper bound (default 65)
If HTF RSI is inside the defined band (e.g. 45–65), signals are blocked (no-trade regime), helping to avoid noisy mid-range conditions.
You can turn this filter ON/OFF and adjust the band dynamically.
🧱 5m OB / Direction Filter (Optional)
Toggle: Use 5m OB direction filter
Timeframe: Configurable (default: 5m).
Uses a simple directional proxy on the OB timeframe:
For BUY signals → require a bullish candle on OB timeframe.
For SELL signals → require a bearish candle on OB timeframe.
When enabled, this adds an extra layer of confluence by aligning entries with the short-term directional context.
⚙️ Key Inputs (Summary)
Timeframes
HTF (Peak Reaction & Structure): default 60 (1H)
Peak Reaction
Lookback bars (HTF)
ATR multiplier for zones
Show/Hide Peak Mid line
Structure
Pivot left/right bars (for HH/HL/LH/LL swings)
Toggle structure labels (HTF & LTF)
Confirmation
Max LTF bars after HTF trigger (default 10, fully configurable)
RSI Filter
Use filter (on/off)
RSI length
No-trade range (low/high)
5m OB Filter
Use filter (on/off)
OB timeframe (default 5m)
📡 Alerts & Automation
The script includes alertconditions for both BUY and SELL signals, with JSON-formatted alert messages suitable for routing to external bridges (e.g. bots, MT5/MT4, n8n, etc.).
Each alert includes:
Symbol
Side (BUY / SELL)
Price / Entry
SL & TP placeholders (from hidden plots, ready to be wired to your own logic)
Time
Performance tag
CommentCode (for strategy/type tagging on the receiver side)
You can attach these alerts to a webhook and let your execution engine handle SL/TP and order management.
📌 How to Use
Attach the indicator to a 1-minute chart.
Set HTF timeframe to 60 (or your preferred higher timeframe).
Optionally enable:
RSI regime filter
5m OB direction filter
Watch for:
Price relative to the Peak Mid line
BUY/SELL triangles that respect HTF structure + LTF confirmation + filters.
For automation, create alerts using the built-in conditions and your preferred JSON alert template.
⚠️ Disclaimer
This tool is for educational and informational purposes only.
It is not financial advice and does not guarantee profits. Always test thoroughly in replay / paper trading before using with live funds, and trade at your own risk.
Volume with High-Volume Highlight + ThresholdThis indicator highlights true high-volume candles without guessing.
It compares the current bar’s volume to the average volume over the last X candles and highlights bars that exceed your chosen threshold (ex: 1.5× the average).
Features
Automatic high-volume detection
Customizable volume multiplier
Bull/bear color coding
Average volume line
Threshold line (shows exactly where “high volume” begins)
Optional on-chart label showing the required volume level
Alert for any high-volume bar
What It’s Used For
Identifying breakout strength
Confirming bounce setups at key levels
Spotting real buyers/sellers stepping in
Avoiding fake moves with weak volume
Simple Rule
If volume is greater than (Average × Multiplier) → the bar is highlighted.
Fed Net Liquidity [Premium] [by Golman Armi]This indicator visualizes the USD Net Liquidity injected into the financial system by the Federal Reserve.
It is a fundamental macro-economic tool essential for understanding the underlying "fuel" driving risk assets such as the S&P 500 (SPX), Nasdaq (NDX), and Bitcoin (BTC).
Unlike many other liquidity scripts that incorrectly use Commercial Bank Assets (USCBBS), this script uses the Federal Reserve Total Assets (WALCL) to provide a mathematically accurate representation of Central Bank liquidity.
How It Works (The Formula)
Net Liquidity represents the actual cash available to the banking system for investment after government liabilities are subtracted. The formula used is:
NetLiquidity=WALCL−TGA−RRP
Where:
WALCL (Fed Balance Sheet): The total assets held by the Federal Reserve (The source of money printing).
TGA (Treasury General Account - WTREGEN): The checking account of the US Government. When the TGA goes up, money is removed from the economy; when it goes down, money is spent into the economy.
RRP (Reverse Repo - RRPONTTLD): Cash parked by banks and money market funds at the Fed overnight. A rise in RRP removes liquidity from the markets.
Features
Accurate Data Sourcing: Pulls daily data directly from FRED (Federal Reserve Economic Data).
Unit Correction: Automatically adjusts conflicting units (Millions vs Billions) from TradingView data feeds to output a correct value in Trillions of Dollars.
Trend Cloud: Features a smoothing EMA (Exponential Moving Average) with a color-coded cloud to easily identify the macro trend (Green for expansion, Red for contraction).
How to Use
Trend Correlation:
Rising Line (Green): Liquidity is expanding. Historically, this supports bullish trends in stocks and crypto.
Falling Line (Red): Liquidity is being drained (QT or TGA refill). This often leads to volatility or bearish trends in risk assets.
Divergences (The most powerful signal):
If the S&P 500 or Bitcoin makes a New High, but Net Liquidity makes a Lower High, it indicates a "hollow rally" lacking fundamental support, often preceding a correction.
Disclaimer
This tool is for educational purposes and macro-economic analysis only. It is not financial advice.
SPX Expected High & Low Move, S&R (Daily Manual update Req)This script enables users to manually plot the anticipated low and high price movements, while also visualizing both positive and negative gamma exposures. The anticipated low represents the projected downside threshold based on expected volatility, whereas the anticipated high reflects the potential upside boundary under similar conditions. Positive gamma indicates scenarios where option positions benefit from underlying price movements, enhancing convexity and reducing directional risk. Conversely, negative gamma highlights exposures where option positions lose value as the underlying price moves, amplifying directional risk and requiring active hedging.
I use Barchart to manually update my personal chart each morning. I am not responsible for any information presented on their website. This is a reference to determine when and where to take profit etc.
Credit Spread RegimeThe Credit Market as Economic Barometer
Credit spreads are among the most reliable leading indicators of economic stress. When corporations borrow money by issuing bonds, investors demand a premium above the risk-free Treasury rate to compensate for the possibility of default. This premium, known as the credit spread, fluctuates based on perceptions of economic health, corporate profitability, and systemic risk.
The relationship between credit spreads and economic activity has been studied extensively. Two papers form the foundation of this indicator. Pierre Collin-Dufresne, Robert Goldstein, and Spencer Martin published their influential 2001 paper in the Journal of Finance, documenting that credit spread changes are driven by factors beyond firm-specific credit quality. They found that a substantial portion of spread variation is explained by market-wide factors, suggesting credit spreads contain information about aggregate economic conditions.
Simon Gilchrist and Egon Zakrajsek extended this research in their 2012 American Economic Review paper, introducing the concept of the Excess Bond Premium. They demonstrated that the component of credit spreads not explained by default risk alone is a powerful predictor of future economic activity. Elevated excess spreads precede recessions with remarkable consistency.
What Credit Spreads Reveal
Credit spreads measure the difference in yield between corporate bonds and Treasury securities of similar maturity. High yield bonds, also called junk bonds, carry ratings below investment grade and offer higher yields to compensate for greater default risk. Investment grade bonds have lower yields because the probability of default is smaller.
The spread between high yield and investment grade bonds is particularly informative. When this spread widens, investors are demanding significantly more compensation for taking on credit risk. This typically indicates deteriorating economic expectations, tighter financial conditions, or increasing risk aversion. When the spread narrows, investors are comfortable accepting lower premiums, signaling confidence in corporate health.
The Gilchrist-Zakrajsek research showed that credit spreads contain two distinct components. The first is the expected default component, which reflects the probability-weighted cost of potential defaults based on corporate fundamentals. The second is the excess bond premium, which captures additional compensation demanded beyond expected defaults. This excess premium rises when investor risk appetite declines and financial conditions tighten.
The Implementation Approach
This indicator uses actual option-adjusted spread data from the Federal Reserve Economic Database (FRED), available directly in TradingView. The ICE BofA indices represent the industry standard for measuring corporate bond spreads.
The primary data sources are FRED:BAMLH0A0HYM2, the ICE BofA US High Yield Index Option-Adjusted Spread, and FRED:BAMLC0A0CM, the ICE BofA US Corporate Index Option-Adjusted Spread for investment grade bonds. These indices measure the spread of corporate bonds over Treasury securities of similar duration, expressed in basis points.
Option-adjusted spreads account for embedded options in corporate bonds, providing a cleaner measure of credit risk than simple yield spreads. The methodology developed by ICE BofA is widely used by institutional investors and central banks for monitoring credit conditions.
The indicator offers two modes. The HY-IG excess spread mode calculates the difference between high yield and investment grade spreads, isolating the pure compensation for below-investment-grade credit risk. This measure is less affected by broad interest rate movements. The HY-only mode tracks the absolute high yield spread, capturing both credit risk and the overall level of risk premiums in the market.
Interpreting the Regimes
Credit conditions are classified into four regimes based on Z-scores calculated from the spread proxy.
The Stress regime occurs when spreads reach extreme levels, typically above a Z-score of 2.0. At this point, credit markets are pricing in significant default risk and economic deterioration. Historically, stress regimes have coincided with recessions, financial crises, and major market dislocations. The 2008 financial crisis, the 2011 European debt crisis, the 2016 commodity collapse, and the 2020 pandemic all triggered credit stress regimes.
The Elevated regime, between Z-scores of 1.0 and 2.0, indicates above-normal risk premiums. Credit conditions are tightening. This often occurs in the build-up to stress events or during periods of uncertainty. Risk management should be heightened, and exposure to credit-sensitive assets may be reduced.
The Normal regime covers Z-scores between -1.0 and 1.0. This represents typical credit conditions where spreads fluctuate around historical averages. Standard investment approaches are appropriate.
The Low regime occurs when spreads are compressed below a Z-score of -1.0. Investors are accepting below-average compensation for credit risk. This can indicate complacency, strong economic confidence, or excessive risk-taking. While often associated with favorable conditions, extremely tight spreads sometimes precede sudden reversals.
Credit Cycle Dynamics
Beyond static regime classification, the indicator tracks the direction and acceleration of spread movements. This reveals where credit markets stand in the credit cycle.
The Deteriorating phase occurs when spreads are elevated and continuing to widen. Credit conditions are actively worsening. This phase often precedes or coincides with economic downturns.
The Recovering phase occurs when spreads are elevated but beginning to narrow. The worst may be over. Credit conditions are improving from stressed levels. This phase often accompanies the early stages of economic recovery.
The Tightening phase occurs when spreads are low and continuing to compress. Credit conditions are very favorable and improving further. This typically occurs during strong economic expansions but may signal building complacency.
The Loosening phase occurs when spreads are low but beginning to widen from compressed levels. The extremely favorable conditions may be normalizing. This can be an early warning of changing sentiment.
Relationship to Economic Activity
The predictive power of credit spreads for economic activity is well-documented. Gilchrist and Zakrajsek found that the excess bond premium predicts GDP growth, industrial production, and unemployment rates over horizons of one to four quarters.
When credit spreads spike, the cost of corporate borrowing increases. Companies may delay or cancel investment projects. Reduced investment leads to slower growth and eventually higher unemployment. The transmission mechanism runs from financial conditions to real economic activity.
Conversely, tight credit spreads lower borrowing costs and encourage investment. Easy credit conditions support economic expansion. However, excessively tight spreads may encourage over-leveraging, planting seeds for future stress.
Practical Application
For equity investors, credit spreads provide context for market risk. Equities and credit often move together because both reflect corporate health. Rising credit spreads typically accompany falling stock prices. Extremely wide spreads historically have coincided with equity market bottoms, though timing the reversal remains challenging.
For fixed income investors, spread regimes guide sector allocation decisions. During stress regimes, flight to quality favors Treasuries over corporates. During low regimes, spread compression may offer limited additional return for credit risk, suggesting caution on high yield.
For macro traders, credit spreads complement other indicators of financial conditions. Credit stress often leads equity volatility, providing an early warning signal. Cross-asset strategies may use credit regime as a filter for position sizing.
Limitations and Considerations
FRED data updates with a lag, typically one business day for the ICE BofA indices. For intraday trading decisions, more current proxies may be necessary. The data is most reliable on daily timeframes.
Credit spreads can remain at extreme levels for extended periods. Mean reversion signals indicate elevated probability of normalization but do not guarantee timing. The 2008 crisis saw spreads remain elevated for many months before normalizing.
The indicator is calibrated for US credit markets. Application to other regions would require different data sources such as European or Asian credit indices. The relationship between spreads and subsequent economic activity may vary across market cycles and structural regimes.
References
Collin-Dufresne, P., Goldstein, R.S., and Martin, J.S. (2001). The Determinants of Credit Spread Changes. Journal of Finance, 56(6), 2177-2207.
Gilchrist, S., and Zakrajsek, E. (2012). Credit Spreads and Business Cycle Fluctuations. American Economic Review, 102(4), 1692-1720.
Krishnamurthy, A., and Muir, T. (2017). How Credit Cycles across a Financial Crisis. Working Paper, Stanford University.
Volatility-Dynamic Risk Manager MNQ [HERMAN]Title: Volatility-Dynamic Risk Manager MNQ
Description:
The Volatility-Dynamic Risk Manager is a dedicated risk management utility designed specifically for traders of Micro Nasdaq 100 Futures (MNQ).
Many traders struggle with position sizing because they use a fixed Stop Loss size regardless of market conditions. A 10-point stop might be safe in a slow market but easily stopped out in a high-volatility environment. This indicator solves that problem by monitoring real-time volatility (using ATR) and automatically suggesting the appropriate Stop Loss size and Position Size (Contracts) to keep your dollar risk constant.
Note: This tool is hardcoded for MNQ (Micro Nasdaq) with a tick value calculation of $2 per point.
📈 How It Works
-This script operates on a logical flow that adapts to market behavior:
-Volatility Measurement: It calculates the Average True Range (ATR) over a user-defined length (Default: 14) to gauge the current "speed" of the market.
-State Detection: Based on the current ATR, the script classifies the market into one of three states:
Low Volatility: The market is chopping or moving slowly.
Normal Volatility: Standard trading conditions.
High Volatility: The market is moving aggressively.
Dynamic Stop Loss Selection: Depending on the detected state, the script selects a pre-defined Stop Loss (in points) that you have configured for that specific environment.
Position Sizing Calculation: Finally, it calculates how many MNQ contracts you can trade so that if your Stop Loss is hit, you do not lose more than your defined "Max Risk per Trade."
🧮 Methodology & Calculations
Since this script handles risk management, transparency in calculation is vital.
Here is the exact math used:
ATR Calculation: Contracts = Max Risk / Risk Per Contract
⚙️ Settings
You can fully customize the behavior of the risk manager via the settings panel:
Risk Management
-Max Risk per Trade ($): The maximum amount of USD you are willing to lose on a single trade.
Volatility Thresholds (ATR)
-ATR Length: The lookback period for volatility calculation.
-Upper Limit for LOW Volatility: If ATR is below this number, the market is "Low Volatility."
-Lower Limit for HIGH Volatility: If ATR is above this number, the market is "High Volatility." (Anything between Low and High is considered "Normal").
Stop Loss Settings (Points)
-SL for Low/Normal/High: Define how wide your stop loss should be in points for each of the three market states.
Visual Settings
-Color Theme: Switch between Light and Dark modes.
-Panel Position: Move the dashboard to any corner or center of your chart.
-Panel Size: Adjust the scale (Tiny to Large) to fit your screen resolution.
📊 Dashboard Overview
-The on-screen panel provides a quick-glance summary for live execution:
-Market State: Color-coded status (Green = Low Vol, Orange = Normal, Red = High Vol).
-Current ATR: The live volatility reading.
-Suggested SL: The Stop Loss size you should enter in your execution platform.
-CONTRACTS: The calculated position size.
-Est. Loss: The actual dollar amount you will lose if the stop is hit (usually slightly less than your Max Risk due to rounding down).
Who is this for?
-Discretionary and systematic futures traders on MNQ (/MNQ or MES also works with small adjustments)
-Anyone who wants perfect risk consistency regardless of whether the market is asleep or exploding
-Traders who hate manual position-size calculations on every trade
No repainting
Works on any timeframe
Real-time updates on every bar
Overlay indicator (no signals, pure risk-management tool)
⚠️ Disclaimer
This tool is for informational and educational purposes only. It calculates mathematical position sizes based on user inputs. It does not execute trades, nor does it guarantee profits. Past performance (volatility) is not indicative of future results. Always manually verify your order size before executing trades on your broker platform.
Session Highs and Lows🔑 Key Levels: Session Liquidity & Structure Mapper
The Key Levels indicator is an essential tool for traders as it automatically plots and projects critical Highs and Lows established during key trading sessions. These levels represent major liquidity pools and define the current market structure, serving as high-probability targets, support, or resistance for the remainder of the trading day.
⚙️ Core Functionality
The indicator operates in two distinct modes, tailored for different asset classes:
1. Asset Class Mode (Toggle)
You can switch between two predefined setups depending on the asset you are trading:
Stock Mode (RTH/ETH): Designed for US stocks and futures (e.g., NQ, ES, YM). It tracks and projects levels for Regular Trading Hours (RTH) (09:30-16:00) and Extended Hours (ETH) (16:00-09:30).
Forex/Default Mode (Asia/London/NY): Designed for global markets (e.g., currency pairs). It tracks and projects levels for the three major liquidity sessions: Asia (19:00-03:00), London (03:00-09:30), and New York (09:30-16:00).
🗺️ Key Levels Mapped
The script continuously tracks and plots the most significant structural levels:
Current Session High/Low: The running high and low of the currently active session.
Previous Session High/Low: The confirmed high and low from the most recently completed session. These are often targeted by market makers.
Previous Day High/Low (PDH/PDL): The high and low of the prior 24-hour day, acting as major structural boundaries and a crucial macro market filter.
🎛️ Advanced Liquidity Management
The indicator is built with specific controls for high-level liquidity analysis:
Extend Through Sweeps (Critical Setting):
OFF (Recommended): The projected line is automatically stopped or deleted the moment the price candle wicks or closes past it. This visually confirms that the liquidity at that level has been "swept" or "mitigated."
ON: The line extends indefinitely, treating the level as simple support/resistance, regardless of interaction.
Previous vs. Current View: You can select a checkbox (e.g., Use PREVIOUS London Level) to hide the current session's running levels and only display the static, confirmed high/low from the prior completed session. This helps declutter the chart and focus only on the confirmed structural levels.
Show Older History: Toggle to keep lines from prior days visible, allowing you to track multi-day structural context.
🎯 Trading Application
The lines plotted by the Key Levels indicator provide immediate, actionable information:
Bias Filter: Use the PDH/PDL to determine the overall market context. Trading above the PDH suggests a bullish bias, while trading below the PDL suggests a bearish bias.
Manipulation/Entry: Wait for price to aggressively sweep a Previous Session High/Low (line stops extending). This often signals a liquidity grab or "manipulation" phase. Look for entries in the opposite direction for the main move (Distribution).
Targets: Key levels (especially unmitigated ones) serve as excellent, objective take-profit targets for active trades.
XAUUSD 1m SMC Zones (BOS + Flexible TP Modes + Trailing Runner)//@version=6
strategy("XAUUSD 1m SMC Zones (BOS + Flexible TP Modes + Trailing Runner)",
overlay = true,
initial_capital = 10000,
pyramiding = 10,
process_orders_on_close = true)
//━━━━━━━━━━━━━━━━━━━
// 1. INPUTS
//━━━━━━━━━━━━━━━━━━━
// TP / SL
tp1Pips = input.int(10, "TP1 (pips)", minval = 1)
fixedSLpips = input.int(50, "Fixed SL (pips)", minval = 5)
runnerRR = input.float(3.0, "Runner RR (TP2 = SL * RR)", step = 0.1, minval = 1.0)
// Daily risk
maxDailyLossPct = input.float(5.0, "Max daily loss % (stop trading)", step = 0.5)
maxDailyProfitPct = input.float(20.0, "Max daily profit % (stop trading)", step = 1.0)
// HTF S/R (1H)
htfTF = input.string("60", "HTF timeframe (minutes) for S/R block")
// Profit strategy (Option C)
profitStrategy = input.string("Minimal Risk | Full BE after TP1", "Profit Strategy", options = )
// Runner stop mode (your option 4)
runnerStopMode = input.string( "BE only", "Runner Stop Mode", options = )
// ATR trail settings (only used if ATR mode selected)
atrTrailLen = input.int(14, "ATR Length (trail)", minval = 1)
atrTrailMult = input.float(1.0, "ATR Multiplier (trail)", step = 0.1, minval = 0.1)
// Pip size (for XAUUSD: 1 pip = 0.10 if tick = 0.01)
pipSize = syminfo.mintick * 10.0
tp1Points = tp1Pips * pipSize
slPoints = fixedSLpips * pipSize
baseQty = input.float (1.0, "Base order size" , step = 0.01, minval = 0.01)
//━━━━━━━━━━━━━━━━━━━
// 2. DAILY RISK MANAGEMENT
//━━━━━━━━━━━━━━━━━━━
isNewDay = ta.change(time("D")) != 0
var float dayStartEquity = na
var bool dailyStopped = false
equityNow = strategy.initial_capital + strategy.netprofit
if isNewDay or na(dayStartEquity)
dayStartEquity := equityNow
dailyStopped := false
dailyPnL = equityNow - dayStartEquity
dailyPnLPct = dayStartEquity != 0 ? (dailyPnL / dayStartEquity) * 100.0 : 0.0
if not dailyStopped
if dailyPnLPct <= -maxDailyLossPct
dailyStopped := true
if dailyPnLPct >= maxDailyProfitPct
dailyStopped := true
canTradeToday = not dailyStopped
//━━━━━━━━━━━━━━━━━━━
// 3. 1H S/R ZONES (for direction block)
//━━━━━━━━━━━━━━━━━━━
htOpen = request.security(syminfo.tickerid, htfTF, open)
htHigh = request.security(syminfo.tickerid, htfTF, high)
htLow = request.security(syminfo.tickerid, htfTF, low)
htClose = request.security(syminfo.tickerid, htfTF, close)
// Engulf logic on HTF
htBullPrev = htClose > htOpen
htBearPrev = htClose < htOpen
htBearEngulf = htClose < htOpen and htBullPrev and htOpen >= htClose and htClose <= htOpen
htBullEngulf = htClose > htOpen and htBearPrev and htOpen <= htClose and htClose >= htOpen
// Liquidity sweep on HTF previous candle
htSweepHigh = htHigh > ta.highest(htHigh, 5)
htSweepLow = htLow < ta.lowest(htLow, 5)
// Store last HTF zones
var float htResHigh = na
var float htResLow = na
var float htSupHigh = na
var float htSupLow = na
if htBearEngulf and htSweepHigh
htResHigh := htHigh
htResLow := htLow
if htBullEngulf and htSweepLow
htSupHigh := htHigh
htSupLow := htLow
// Are we inside HTF zones?
inHtfRes = not na(htResHigh) and close <= htResHigh and close >= htResLow
inHtfSup = not na(htSupLow) and close >= htSupLow and close <= htSupHigh
// Block direction against HTF zones
longBlockedByZone = inHtfRes // no buys in HTF resistance
shortBlockedByZone = inHtfSup // no sells in HTF support
//━━━━━━━━━━━━━━━━━━━
// 4. 1m LOCAL ZONES (LIQUIDITY SWEEP + ENGULF + QUALITY SCORE)
//━━━━━━━━━━━━━━━━━━━
// 1m engulf patterns
bullPrev1 = close > open
bearPrev1 = close < open
bearEngulfNow = close < open and bullPrev1 and open >= close and close <= open
bullEngulfNow = close > open and bearPrev1 and open <= close and close >= open
// Liquidity sweep by previous candle on 1m
sweepHighPrev = high > ta.highest(high, 5)
sweepLowPrev = low < ta.lowest(low, 5)
// Local zone storage (one active support + one active resistance)
// Quality score: 1 = engulf only, 2 = engulf + sweep (we only trade ≥2)
var float supLow = na
var float supHigh = na
var int supQ = 0
var bool supUsed = false
var float resLow = na
var float resHigh = na
var int resQ = 0
var bool resUsed = false
// New resistance zone: previous bullish candle -> bear engulf
if bearEngulfNow
resLow := low
resHigh := high
resQ := sweepHighPrev ? 2 : 1
resUsed := false
// New support zone: previous bearish candle -> bull engulf
if bullEngulfNow
supLow := low
supHigh := high
supQ := sweepLowPrev ? 2 : 1
supUsed := false
// Raw "inside zone" detection
inSupRaw = not na(supLow) and close >= supLow and close <= supHigh
inResRaw = not na(resHigh) and close <= resHigh and close >= resLow
// QUALITY FILTER: only trade zones with quality ≥ 2 (engulf + sweep)
highQualitySup = supQ >= 2
highQualityRes = resQ >= 2
inSupZone = inSupRaw and highQualitySup and not supUsed
inResZone = inResRaw and highQualityRes and not resUsed
// Plot zones
plot(supLow, "Sup Low", color = color.new(color.lime, 60), style = plot.style_linebr)
plot(supHigh, "Sup High", color = color.new(color.lime, 60), style = plot.style_linebr)
plot(resLow, "Res Low", color = color.new(color.red, 60), style = plot.style_linebr)
plot(resHigh, "Res High", color = color.new(color.red, 60), style = plot.style_linebr)
//━━━━━━━━━━━━━━━━━━━
// 5. MODERATE BOS (3-BAR FRACTAL STRUCTURE)
//━━━━━━━━━━━━━━━━━━━
// 3-bar swing highs/lows
swHigh = high > high and high > high
swLow = low < low and low < low
var float lastSwingHigh = na
var float lastSwingLow = na
if swHigh
lastSwingHigh := high
if swLow
lastSwingLow := low
// BOS conditions
bosUp = not na(lastSwingHigh) and close > lastSwingHigh
bosDown = not na(lastSwingLow) and close < lastSwingLow
// Zone “arming” and BOS validation
var bool supArmed = false
var bool resArmed = false
var bool supBosOK = false
var bool resBosOK = false
// Arm zones when first touched
if inSupZone
supArmed := true
if inResZone
resArmed := true
// BOS after arming → zone becomes valid for entries
if supArmed and bosUp
supBosOK := true
if resArmed and bosDown
resBosOK := true
// Reset BOS flags when new zones are created
if bullEngulfNow
supArmed := false
supBosOK := false
if bearEngulfNow
resArmed := false
resBosOK := false
//━━━━━━━━━━━━━━━━━━━
// 6. ENTRY CONDITIONS (ZONE + BOS + RISK STATE)
//━━━━━━━━━━━━━━━━━━━
flatOrShort = strategy.position_size <= 0
flatOrLong = strategy.position_size >= 0
longSignal = canTradeToday and not longBlockedByZone and inSupZone and supBosOK and flatOrShort
shortSignal = canTradeToday and not shortBlockedByZone and inResZone and resBosOK and flatOrLong
//━━━━━━━━━━━━━━━━━━━
// 7. ORDER LOGIC – TWO PROFIT STRATEGIES
//━━━━━━━━━━━━━━━━━━━
// Common metrics
atrTrail = ta.atr(atrTrailLen)
// MINIMAL MODE: single trade, BE after TP1, optional trailing
// HYBRID MODE: two trades (Scalp @ TP1, Runner @ TP2)
// Persistent tracking
var float longEntry = na
var float longTP1 = na
var float longTP2 = na
var float longSL = na
var bool longBE = false
var float longRunEntry = na
var float longRunTP1 = na
var float longRunTP2 = na
var float longRunSL = na
var bool longRunBE = false
var float shortEntry = na
var float shortTP1 = na
var float shortTP2 = na
var float shortSL = na
var bool shortBE = false
var float shortRunEntry = na
var float shortRunTP1 = na
var float shortRunTP2 = na
var float shortRunSL = na
var bool shortRunBE = false
isMinimal = profitStrategy == "Minimal Risk | Full BE after TP1"
isHybrid = profitStrategy == "Hybrid | Scalp TP + Runner TP"
//━━━━━━━━━━ LONG ENTRIES ━━━━━━━━━━
if longSignal
if isMinimal
longEntry := close
longSL := longEntry - slPoints
longTP1 := longEntry + tp1Points
longTP2 := longEntry + slPoints * runnerRR
longBE := false
strategy.entry("Long", strategy.long)
supUsed := true
supArmed := false
supBosOK := false
else if isHybrid
longRunEntry := close
longRunSL := longRunEntry - slPoints
longRunTP1 := longRunEntry + tp1Points
longRunTP2 := longRunEntry + slPoints * runnerRR
longRunBE := false
// Two separate entries, each 50% of baseQty (for backtest)
strategy.entry("LongScalp", strategy.long, qty = baseQty * 0.5)
strategy.entry("LongRun", strategy.long, qty = baseQty * 0.5)
supUsed := true
supArmed := false
supBosOK := false
//━━━━━━━━━━ SHORT ENTRIES ━━━━━━━━━━
if shortSignal
if isMinimal
shortEntry := close
shortSL := shortEntry + slPoints
shortTP1 := shortEntry - tp1Points
shortTP2 := shortEntry - slPoints * runnerRR
shortBE := false
strategy.entry("Short", strategy.short)
resUsed := true
resArmed := false
resBosOK := false
else if isHybrid
shortRunEntry := close
shortRunSL := shortRunEntry + slPoints
shortRunTP1 := shortRunEntry - tp1Points
shortRunTP2 := shortRunEntry - slPoints * runnerRR
shortRunBE := false
strategy.entry("ShortScalp", strategy.short, qty = baseQty * 50)
strategy.entry("ShortRun", strategy.short, qty = baseQty * 50)
resUsed := true
resArmed := false
resBosOK := false
//━━━━━━━━━━━━━━━━━━━
// 8. EXIT LOGIC – MINIMAL MODE
//━━━━━━━━━━━━━━━━━━━
// LONG – Minimal Risk: 1 trade, BE after TP1, runner to TP2
if isMinimal and strategy.position_size > 0 and not na(longEntry)
// Move to BE once TP1 is touched
if not longBE and high >= longTP1
longBE := true
// Base SL: BE or initial SL
float dynLongSL = longBE ? longEntry : longSL
// Optional trailing after BE
if longBE
if runnerStopMode == "Structure trail" and not na(lastSwingLow) and lastSwingLow > longEntry
dynLongSL := math.max(dynLongSL, lastSwingLow)
if runnerStopMode == "ATR trail"
trailSL = close - atrTrailMult * atrTrail
dynLongSL := math.max(dynLongSL, trailSL)
strategy.exit("Long Exit", "Long", stop = dynLongSL, limit = longTP2)
// SHORT – Minimal Risk: 1 trade, BE after TP1, runner to TP2
if isMinimal and strategy.position_size < 0 and not na(shortEntry)
if not shortBE and low <= shortTP1
shortBE := true
float dynShortSL = shortBE ? shortEntry : shortSL
if shortBE
if runnerStopMode == "Structure trail" and not na(lastSwingHigh) and lastSwingHigh < shortEntry
dynShortSL := math.min(dynShortSL, lastSwingHigh)
if runnerStopMode == "ATR trail"
trailSLs = close + atrTrailMult * atrTrail
dynShortSL := math.min(dynShortSL, trailSLs)
strategy.exit("Short Exit", "Short", stop = dynShortSL, limit = shortTP2)
//━━━━━━━━━━━━━━━━━━━
// 9. EXIT LOGIC – HYBRID MODE
//━━━━━━━━━━━━━━━━━━━
// LONG – Hybrid: Scalp + Runner
if isHybrid
// Scalp leg: full TP at TP1
if strategy.opentrades > 0
strategy.exit("LScalp TP", "LongScalp", stop = longRunSL, limit = longRunTP1)
// Runner leg
if strategy.position_size > 0 and not na(longRunEntry)
if not longRunBE and high >= longRunTP1
longRunBE := true
float dynLongRunSL = longRunBE ? longRunEntry : longRunSL
if longRunBE
if runnerStopMode == "Structure trail" and not na(lastSwingLow) and lastSwingLow > longRunEntry
dynLongRunSL := math.max(dynLongRunSL, lastSwingLow)
if runnerStopMode == "ATR trail"
trailRunSL = close - atrTrailMult * atrTrail
dynLongRunSL := math.max(dynLongRunSL, trailRunSL)
strategy.exit("LRun TP", "LongRun", stop = dynLongRunSL, limit = longRunTP2)
// SHORT – Hybrid: Scalp + Runner
if isHybrid
if strategy.opentrades > 0
strategy.exit("SScalp TP", "ShortScalp", stop = shortRunSL, limit = shortRunTP1)
if strategy.position_size < 0 and not na(shortRunEntry)
if not shortRunBE and low <= shortRunTP1
shortRunBE := true
float dynShortRunSL = shortRunBE ? shortRunEntry : shortRunSL
if shortRunBE
if runnerStopMode == "Structure trail" and not na(lastSwingHigh) and lastSwingHigh < shortRunEntry
dynShortRunSL := math.min(dynShortRunSL, lastSwingHigh)
if runnerStopMode == "ATR trail"
trailRunSLs = close + atrTrailMult * atrTrail
dynShortRunSL := math.min(dynShortRunSL, trailRunSLs)
strategy.exit("SRun TP", "ShortRun", stop = dynShortRunSL, limit = shortRunTP2)
//━━━━━━━━━━━━━━━━━━━
// 10. RESET STATE WHEN FLAT
//━━━━━━━━━━━━━━━━━━━
if strategy.position_size == 0
longEntry := na
shortEntry := na
longBE := false
shortBE := false
longRunEntry := na
shortRunEntry := na
longRunBE := false
shortRunBE := false
//━━━━━━━━━━━━━━━━━━━
// 11. VISUAL ENTRY MARKERS
//━━━━━━━━━━━━━━━━━━━
plotshape(longSignal, title = "Long Signal", style = shape.triangleup,
location = location.belowbar, color = color.lime, size = size.tiny, text = "L")
plotshape(shortSignal, title = "Short Signal", style = shape.triangledown,
location = location.abovebar, color = color.red, size = size.tiny, text = "S")
Absorption RatioThe Hidden Connections Between Markets
Financial markets are not isolated islands. When panic spreads, seemingly unrelated assets suddenly begin moving in lockstep. Stocks, bonds, commodities, and currencies that normally provide diversification benefits start falling together. This phenomenon, where correlations spike during crises, has devastated portfolios throughout history. The Absorption Ratio provides a quantitative measure of this hidden fragility.
The concept emerged from research at State Street Associates, where Mark Kritzman, Yuanzhen Li, Sebastien Page, and Roberto Rigobon developed a novel application of principal component analysis to measure systemic risk. Their 2011 paper in the Journal of Portfolio Management demonstrated that when markets become tightly coupled, the variance explained by the first few principal components increases dramatically. This concentration of variance signals elevated systemic risk.
What the Absorption Ratio Measures
Principal component analysis, or PCA, is a statistical technique that identifies the underlying factors driving a set of variables. When applied to asset returns, the first principal component typically captures broad market movements. The second might capture sector rotations or risk-on/risk-off dynamics. Additional components capture increasingly idiosyncratic patterns.
The Absorption Ratio measures the fraction of total variance absorbed or explained by a fixed number of principal components. In the original research, Kritzman and colleagues used the first fifth of the eigenvectors. When this fraction is high, it means a small number of factors are driving most of the market movements. Assets are moving together, and diversification provides less protection than usual.
Consider an analogy: imagine a room full of people having independent conversations. Each person speaks at different times about different topics. The total "variance" of sound in the room comes from many independent sources. Now imagine a fire alarm goes off. Suddenly everyone is talking about the same thing, moving in the same direction. The variance is now dominated by a single factor. The Absorption Ratio captures this transition from diverse, independent behavior to unified, correlated movement.
The Implementation Approach
TradingView does not support matrix algebra required for true principal component analysis. This implementation uses a closely related proxy: the average absolute correlation across a universe of major asset classes. This approach captures the same underlying phenomenon because when assets are highly correlated, the first principal component explains more variance by mathematical necessity.
The asset universe includes eight ETFs representing major investable categories: SPY and QQQ for large cap US equities, IWM for small caps, EFA for developed international markets, EEM for emerging markets, TLT for long-term treasuries, GLD for gold, and USO for oil. This selection provides exposure to equities across geographies and market caps, plus traditional diversifying assets.
From eight assets, there are twenty-eight unique pairwise correlations. The indicator calculates each using a rolling window, takes the absolute value to measure coupling strength regardless of direction, and averages across all pairs. This average correlation is then transformed to match the typical range of published Absorption Ratio values.
The transformation maps zero average correlation to an AR of 0.50 and perfect correlation to an AR of 1.00. This scaling aligns with empirical observations that the AR typically fluctuates between 0.60 and 0.95 in practice.
Interpreting the Regimes
The indicator classifies systemic risk into four regimes based on AR levels.
The Extreme regime occurs when the AR exceeds 0.90. At this level, nearly all asset classes are moving together. Diversification has largely failed. Historically, this regime has coincided with major market dislocations: the 2008 financial crisis, the 2020 COVID crash, and significant correction periods. Portfolios constructed under normal correlation assumptions will experience larger drawdowns than expected.
The High regime, between 0.80 and 0.90, indicates elevated systemic risk. Correlations across asset classes are above normal. This often occurs during the build-up to stress events or during volatile periods where fear is spreading but has not reached panic levels. Risk management should be more conservative.
The Normal regime covers AR values between 0.60 and 0.80. This represents typical market conditions where some correlation exists between assets but diversification still provides meaningful benefits. Standard portfolio construction assumptions are reasonable.
The Low regime, below 0.60, indicates that assets are behaving relatively independently. Diversification is working well. Idiosyncratic factors dominate returns rather than systematic risk. This environment is favorable for active management and security selection strategies.
The Relationship to Portfolio Construction
The implications for portfolio management are significant. Modern portfolio theory assumes correlations are stable and uses historical estimates to construct efficient portfolios. The Absorption Ratio reveals that this assumption is violated precisely when it matters most.
When AR is elevated, the effective number of independent bets in a diversified portfolio shrinks. A portfolio holding stocks, bonds, commodities, and real estate might behave as if it holds only one or two positions during high AR periods. Position sizing based on normal correlation estimates will underestimate portfolio risk.
Conversely, when AR is low, true diversification opportunities expand. The same nominal portfolio provides more independent return streams. Risk can be deployed more aggressively while maintaining the same effective exposure.
Component Analysis
The indicator separately tracks equity correlations and cross-asset correlations. These components tell different stories about market structure.
Equity correlations measure coupling within the stock market. High equity correlation indicates broad risk-on or risk-off behavior where all stocks move together. This is common during both rallies and selloffs driven by macroeconomic factors. Stock pickers face headwinds when equity correlations are elevated because individual company fundamentals matter less than market beta.
Cross-asset correlations measure coupling between different asset classes. When stocks, bonds, and commodities start moving together, traditional hedges fail. The classic 60/40 stock/bond portfolio, for example, assumes negative or low correlation between equities and treasuries. When cross-asset correlation spikes, this assumption breaks down.
During the 2022 market environment, for instance, both stocks and bonds fell significantly as inflation and rate hikes affected all assets simultaneously. High cross-asset correlation warned that the usual defensive allocations would not provide their expected protection.
Mean Reversion Characteristics
Like most risk metrics, the Absorption Ratio tends to mean-revert over time. Extremely high AR readings eventually normalize as panic subsides and assets return to more independent behavior. Extremely low readings tend to rise as some level of systematic risk always reasserts itself.
The indicator tracks AR in statistical terms by calculating its Z-score relative to the trailing distribution. When AR reaches extreme Z-scores, the probability of normalization increases. This creates potential opportunities for strategies that bet on mean reversion in systemic risk.
A buy signal triggers when AR recovers from extremely elevated levels, suggesting the worst of the correlation spike may be over. A sell signal triggers when AR rises from unusually low levels, warning that complacency about diversification benefits may be excessive.
Momentum and Trend
The rate of change in AR carries information beyond the absolute level. Rapidly rising AR suggests correlations are increasing and systemic risk is building. Even if AR has not yet reached the high regime, acceleration in coupling should prompt increased vigilance.
Falling AR momentum indicates normalizing conditions. Correlations are decreasing and assets are returning to more independent behavior. This often occurs in the recovery phase following stress events.
Practical Application
For asset allocators, the AR provides guidance on how much diversification benefit to expect from a given allocation. During high AR periods, reducing overall portfolio risk makes sense because the usual diversifiers provide less protection. During low AR periods, standard or even aggressive allocations are more appropriate.
For risk managers, the AR serves as an early warning indicator. Rising AR often precedes large market moves and volatility spikes. Tightening risk limits before correlations reach extreme levels can protect capital.
For systematic traders, the AR provides a regime filter. Mean reversion strategies may work better during high AR periods when panics create overshooting. Momentum strategies may work better during low AR periods when trends can develop independently across assets.
Limitations and Considerations
The proxy methodology introduces some approximation error relative to true PCA-based AR calculations. The asset universe, while representative, does not include all possible diversifiers. Correlation estimates are inherently backward-looking and can change rapidly.
The transformation from average correlation to AR scale is calibrated to match typical published ranges but is not mathematically equivalent to the eigenvalue ratio. Users should interpret levels directionally rather than as precise measurements.
Correlation regimes can persist longer than expected. Mean reversion signals indicate elevated probability of normalization but do not guarantee timing. High AR can remain elevated throughout extended crisis periods.
References
Kritzman, M., Li, Y., Page, S., and Rigobon, R. (2011). Principal Components as a Measure of Systemic Risk. Journal of Portfolio Management, 37(4), 112-126.
Kritzman, M., and Li, Y. (2010). Skulls, Financial Turbulence, and Risk Management. Financial Analysts Journal, 66(5), 30-41.
Billio, M., Getmansky, M., Lo, A., and Pelizzon, L. (2012). Econometric Measures of Connectedness and Systemic Risk in the Finance and Insurance Sectors. Journal of Financial Economics, 104(3), 535-559.
Delta Bars [Elykia]Delta Bars — Order Flow & Momentum Analysis
Description:
Delta Bars is an "Order Flow Oscillator" designed to instantly visualize buyer and seller aggression within every price move.
Unlike standard volume, it breaks down what is happening "under the hood" (Delta) and offers a clear reading of market reversals thanks to intelligent divergence detection.
🔥 Key Features:
1. Dual Calculation Mode:
Timeframe Mode: Displays classic Delta based on time (e.g., 1min, 5min).
Range Bars Mode: (Exclusive) Builds Delta bars based on price movement (volatility) rather than time. This filters out noise during consolidation periods and reveals true strength during impulses.
2. 🧠 Smart Auto-Detection (Plug & Play):
No need to manually calculate "Box" or "Tick" sizes for each asset. The indicator automatically recognizes the asset you are trading and applies the optimal institutional calibration:
US Indices (NQ, ES, YM...)
Forex (EURUSD, JPY...)
Crypto (BTC, ETH)
Commodities (Gold, Oil)
Note: You can still switch to manual mode if needed.
3. "Flip" Detection (Divergences) ⚡:
The indicator automatically identifies anomalies between price and Delta:
If the candle closes Green but Delta is Negative (Absorption/Failed Selling Effort).
If the candle closes Red but Delta is Positive.
These situations are marked with a ⚡ symbol and a specific highlight color (Orange by default), often signaling an imminent reversal.
4. Technical Dashboard:
A discreet panel displays the current mode and "Box" size (in ticks/points) in real-time, ensuring you always know how the data is being filtered.
How to read the signals?
1. Green/Red Bars: They indicate Net Delta (the difference between buying and selling volume). A tall bar implies strong conviction.
2. The ⚡ Symbol (The Flip): This is the most critical signal. It appears when Delta contradicts the candle direction (e.g., Positive Delta on a Bearish candle). This indicates Absorption (passive orders blocking the move) and often precedes a reversal.
3. Range Bars Mode: Use this mode to "smooth out" the market. If the market is choppy, Range Bars will filter the noise and only draw a new bar if the price actually moves.
⚠️ Important: Replay Mode
Since this indicator performs heavy calculations (simulated tick-by-tick), it includes a safety feature for Replay Mode.
To use Replay: Go to settings and set the "Force Replay Date" to a date close to your starting point. This ensures maximum fluidity and avoids TradingView limit errors.
Configuration:
Works on all timeframes but excels on seconds charts (1s, 5s) or fast minute charts (1m) for scalping.
TRADE ORBIT – Ichimoku Top/Bottom Strategy)TRADE ORBIT – Ichimoku Top/Bottom Strategy
Trade when trends start, continue, and end
✅ BUY TRADE (LONG)
Entry
Enter a BUY only if all of the following happen:
1️⃣ Green Big Dot appears below candle
→ Bottom confirmed (trend reversal)
2️⃣ Price above the Cloud
→ Market is in bullish zone
3️⃣ Tenkan above Kijun
→ Short-term trend supports direction
4️⃣ Chikou Span above price
→ Confirmation from momentum
📍 Best entry:
➡ On the candle after the big green dot if conditions remain valid
Stop Loss
Place SL below:
⭕ Bottom candle low
or
⭕ Senkou Span B (Cloud bottom)
Profit Management
Stay in the trade as long as you keep seeing small green dots
→ Trend still continuing 🟢🟢🟢
📌 Exit long when:
A big red dot appears (Top detected)
or
Price closes below the cloud
or
Tenkan crosses below Kijun
❌ SELL TRADE (SHORT)
Entry
Enter SELL only if:
1️⃣ Big Red Dot appears above candle
→ Top confirmed
2️⃣ Price below Cloud
→ Bearish market
3️⃣ Tenkan below Kijun
→ Trend aligned
4️⃣ Chikou Span below price
→ Momentum confirmed
📍 Enter on next bar if signals remain valid
Stop Loss
Place SL above:
⭕ Top candle high
or
⭕ Senkou Span B (Cloud upper band)
Exit
Stay in short while small red dots continue 🔴🔴🔴
Close when:
A big green bottom dot appears
or
Price closes above cloud
or
Tenkan crosses above Kijun
Setup Keltner Banda 3 e 5 - MMS + RSI + Distância Tabela
📊 Indicator Overview: Keltner Bands + RSI + Distance Table
This custom TradingView indicator combines three powerful tools into a single, visually intuitive setup:
Keltner Channels (Bands 3x and 5x ATR)
Relative Strength Index (RSI)
Dynamic Table Displaying RSI and Price Distance from Moving Average (MMS)
🔧 Components and Functions
1. Keltner Channels (3x and 5x ATR)
Based on a Simple Moving Average (MMS) and Average True Range (ATR).
Two sets of bands are plotted:
3x ATR Bands: Used for moderate volatility signals.
5x ATR Bands: Used for high volatility extremes.
Visual fills between bands help identify overextended price zones.
2. RSI (Relative Strength Index)
Measures momentum and potential reversal zones.
Customizable overbought (default 70) and oversold (default 30) levels.
RSI values are color-coded in the table:
Green for RSI ≤ 30 (oversold)
Blue for 30 < RSI ≤ 70 (neutral)
Red for RSI > 70 (overbought)
3. Distance Table (Price vs. MMS)
Displays the real-time distance between the current price and the MMS:
In points (absolute difference)
In percentage (relative to MMS)
Helps traders assess how far price has deviated from its mean.
📈 How to Use
Trend Reversal Signals
Look for price crossing back inside the 3x or 5x Keltner Bands.
Confirm with RSI:
RSI > 70 + price re-entering from above = potential short
RSI < 30 + price re-entering from below = potential long
Volatility Zones
Price outside the 5x band indicates extreme movement.
Use this to anticipate mean reversion or breakout continuation.
Table Insights
Monitor RSI and price distance in real time.
Use color cues to quickly assess momentum and stretch.
⚙️ Customization
Adjustable parameters for:
MMS period
ATR multipliers
RSI period and thresholds
Table position on chart
Fill colors between bands
This indicator is ideal for traders who want a clean, data-rich visual tool to track volatility, momentum, and price deviation in one place.
VIX + Weekly ATR Hybrid RangeVIX + Weekly ATR Hybrid Range VIX + Weekly ATR Hybrid Range VIX + Weekly ATR Hybrid Range
Gartley Pattern ULTRA V6[NXT2017]+VolumeProfile+POC+SignalCountsGartley Pattern ULTRA V6 is a professional harmonic scanner designed to automatically detect and visualize valid Gartley patterns across multiple pivot lengths. Unlike standard indicators, this script includes advanced institutional tools like Volume Profile integration per pattern and a statistical dashboard.
Key Features: Multi-Pivot Scanning: Scans for patterns simultaneously across 9 different pivot lengths (from 5 to 233) to find structures on micro and macro levels. Volume Profile Integration: Automatically draws a Volume Profile (VP) covering the range from Point X to the current bar to analyze supply and demand within the pattern structure. POC Indication: Highlights the Point of Control (POC) to identify key support/resistance levels within the pattern. Statistics Dashboard: A table displaying the number of Bullish and Bearish patterns found for each pivot size. Customizable: Full control over colors, tolerance levels, and display options.
The Gartley Pattern Rules Used: This script strictly follows the classic ratios for the Gartley pattern: B Point: Strictly a 0.618 retracement of the XA leg. C Point: Retracement of AB (0.382 – 0.886). Crucially, Point C must not exceed Point A. D Point (Entry): The defining characteristic is the 0.786 retracement of the XA leg . Point D must not exceed Point X.
Settings & Inputs: Deviation Tolerance: Adjust the strictness of the ratio matching (default 30% allows for market noise). Volume Profile: Toggle the VP on/off, adjust resolution (rows), and transparency. Filter & History: Prevents duplicate signals for the same price structure.
How to use: Add the indicator to your chart. Bullish Gartleys are highlighted in Green and Bearish Gartleys in Fuchsia. The pattern completes at the D-point (78.6% of XA). Use the Volume Profile to confirm if the reversal is happening at a high-volume node.
This is a update of v1:
Vegas plus by stanleyThis Pine Script implements a comprehensive trend-following strategy known popularly as the **Vegas Tunnel Method**. It combines multiple Exponential Moving Averages (EMAs) to define trends, pullbacks, and breakouts.
Here is a step-by-step walkthrough of how the code works, broken down by its components and logic.
---
### 1. The Anatomy (The Indicators)
The script uses three distinct groups of Moving Averages to define the market structure.
#### A. The Fast EMAs (The Trigger & Exit)
* **EMA 12 (Signal):** The fastest line. It is used to trigger entries (crossing the tunnel).
* **EMA 21 (Exit):** Used as a trailing stop. If the price crosses this line against your trade, the script signals an exit.
* **EMA 55 (Filter):** A medium-term filter, often used visually to gauge trend health.
#### B. The "Hero" Tunnel (The Action Zone)
* **EMAs 144 & 169 & 200:** These creates the main "Tunnel."
* **Function:** This acts as dynamic Support and Resistance.
* **Bullish:** If the 144 (Top) is above the 200 (Bottom), the tunnel is painted Blue.
* **Bearish:** If the 144 is below the 200, it is painted Red.
#### C. The "Anchor" Tunnel (The Deep Trend)
* **EMAs 576 & 676:** This creates a massive, slow-moving background tunnel.
* **Function:** It tells you the long-term trend. Generally, you only want to take Buy signals if price is above this Anchor, though the script logic focuses primarily on the Hero tunnel for triggers.
---
### 2. State Memory (`var` Variables)
This is a sophisticated part of the script. It uses `var` variables to "remember" where the price was in the past.
* `originPrice`: Remembers if the price was last seen **Above** (1) or **Below** (-1) the tunnel.
* `originEMA`: Remembers if the EMA 12 was last seen **Above** (1) or **Below** (-1) the tunnel.
**Why is this needed?**
To distinguish between a **Breakout** (crossing from Bear to Bull) and a **Pullback** (already Bull, dipped into tunnel, and coming back out).
---
### 3. The Four Entry Triggers
The script looks for four specific scenarios to generate a Buy or Sell signal. You can turn these on/off in the settings.
#### Trigger 1: Price U-Turn (Trend Continuation)
* **Logic:** The Price was *already* above the tunnel (`originPrice == 1`), dipped down, and is now crossing back up (`crossover`).
* **Meaning:** This is a classic "Buy the Dip" signal within an existing trend.
#### Trigger 2: EMA U-Turn (Lagging Confirmation)
* **Logic:** Similar to Trigger 1, but uses the **EMA 12** line instead of the Price candle.
* **Meaning:** This is safer but slower. It waits for the average price to curl back out of the tunnel.
#### Trigger 3: Breakthrough (Momentum Shift)
* **Logic:** The EMA 12 was previously *below* the tunnel (`originEMA == -1`) and has just crossed *above* it (`crossover`).
* **Meaning:** This is a Trend Reversal signal. The market has shifted from Bearish to Bullish.
#### Trigger 4: Wick Rejection (Touch & Go)
* **Logic:**
1. Price is generally above the tunnel.
2. The `Low` of the current candle touches the tunnel.
3. The `Low` of the *previous* candle did NOT touch the tunnel.
4. The candle closes *outside* (above) the tunnel.
* **Meaning:** The price tested the support zone and was immediately rejected (bounced off), leaving a wick.
---
### 4. Trade Management (State Machine)
The script uses a variable called `tradeState` to manage signals so they don't spam your chart.
* `tradeState = 0`: Flat (No position).
* `tradeState = 1`: Long.
* `tradeState = -1`: Short.
**The Rules:**
1. **Entry:** If `validLong` is triggered AND `tradeState` is not already 1 -> Change state to 1 (Long) and plot a **BUY** label.
2. **Holding:** If you are already in State 1, the script ignores new Buy signals.
3. **Exit:** If `tradeState` is 1 AND price closes below EMA 21 -> Change state to 0 (Flat) and plot an **Exit L** label.
---
### 5. Visual Summary
* **Green Label:** Buy Signal (Long Entry).
* **Red Label:** Sell Signal (Short Entry).
* **Grey X:** Exit Signal (Close the position).
* **Blue/Red Tunnel:** The "Hero" tunnel (144/169/200).
* **Grey Background Tunnel:** The "Anchor" tunnel (576/676).
### How to read the signals:
You are looking for the price to interact with the **Hero Tunnel** (the thinner, brighter one).
1. **Trend:** Look at the slope of the Anchor (thick grey) tunnel.
2. **Setup:** Wait for price to come back to the Hero Tunnel.
3. **Trigger:** Wait for a **Green Label**. This means the price dipped into the tunnel and is now blasting out (U-Turn), or has rejected the tunnel (Wick), or has broken through a new trend (Breakthrough).
4. **Exit:** Close the trade when the **Grey X** appears (Price crosses the EMA 21).
CypherPattern ULTRA V6 [NXT2017]+VolumeProfile+POC +SignalCountsCypher Pattern ULTRA V6 is a comprehensive harmonic scanner designed to automatically detect and visualize valid Cypher patterns across multiple pivot lengths. Unlike standard harmonic indicators, this script includes advanced features like Volume Profile integration per pattern and a statistical dashboard.
Key Features: Multi-Pivot Scanning: Scans for patterns simultaneously across 9 different pivot lengths (from 5 to 233) to find structures on micro and macro levels. Volume Profile Integration: Automatically draws a Volume Profile (VP) covering the range from Point X to the current bar to analyze supply and demand within the pattern structure. POC Indication: Highlights the Point of Control (POC) to identify key support/resistance levels within the pattern. Statistics Dashboard: A table displaying the number of Bullish and Bearish patterns found for each pivot size. Customizable: Full control over colors, tolerance levels, and display options.
The Cypher Pattern Rules Used: This script strictly follows the specific ratios for the Cypher pattern: B Point: 0.382 – 0.618 retracement of the XA leg. C Point: 1.13 – 1.414 extension of the AB leg (C projects beyond A). D Point (Entry): The unique characteristic of the Cypher is that the D point is the 0.786 retracement of the XC leg (not XA).
Settings & Inputs: Deviation Tolerance: Adjust the strictness of the ratio matching (default 30%). Volume Profile: Toggle the VP on/off, adjust resolution (rows), and transparency. Filter & History: Prevents duplicate signals for the same price structure.
How to use: Add the indicator to your chart. Bullish patterns are highlighted in Green (default) and Bearish patterns in Pink/Fuchsia. Look for the D-point completion for potential reversal entries. Use the Volume Profile to confirm if the reversal is happening at a high-volume node.






















