Universal Longs Vs. Shorts - Ratio (Any Symbol)Hello again all my Trading View friends!
This script is a variation of my other script "Universal Longs Vs. Shorts - Percentage (Any Symbol)"
It allows you to choose ANY symbol and plot the ratio against ANY other symbol, as an indicator on your given pair. It is primarily used as an indicator of longs/shorts as well as shorts/longs as a ratio to each other.
For example, you could plot BITFINEX:BTCUSDLONGS against BITFINEX:BTCUSDSHORTS.
It plots the ratio of longs/shorts or shorts/longs. For example:
If there are more longs than shorts open, the long ratio will be great than 1 with no upper limit.
If there are less longs than shorts open, the ratio will be less than 1 but greater than 0.
The same is true when comparing shorts to longs. You can choose to view Longs Ratio only, Shorts Ratio only, or Both.
This is useful to see how many more longs there are than shorts, and visa versa, at any given time interval. It does not take into consideration total volume of longs + shorts to get an absolute number, but rather a relative ratio to each other.
If there are many more positions open in one direction over the other, the ratio will rise higher and higher away from 1, which lets you know generally that there is a lot greater volume of that position open compared to its reverse.
If you found this script helpful please remember to FOLLOW and press LIKE!!
More useful scripts to come :-D
Поиск скриптов по запросу "bear"
Universal Longs Vs. Shorts - Percentage (Any Symbol)Hello all my Trading View friends!!
This script allows you to choose ANY symbol and plot the ratio against ANY other symbol, as an indicator on your given pair. It is primarily used as an indicator of longs/shorts as well as shorts/longs as a percentage of total longs + shorts.
For example, you could plot BITFINEX:BTCUSDLONGS against BITFINEX:BTCUSDSHORTS.
It takes the ratio from an absolute 100%, rather than relative to each other. Therefore, each plot has a minimum of 0% and a maximum of 100%. You can choose to view Longs Percentage only, Shorts Percentage only, or Both.
This is useful to see what percentage of total positions are either long or short at any given time interval.
If you found this script helpful please remember to FOLLOW and press LIKE!!
NG [Simple Harmonic Oscillator]The SHO is a bounded oscillator for the simple harmonic index that calculates the period of the market’s cycle.
The oscillator is used for short and intermediate terms and moves within a range of -100 to 100 percent.
The SHO has overbought and oversold levels at +40 and -40, respectively.
At extreme periods, the oscillator may reach the levels of +60 and -60.
The zero level demonstrates an equilibrium between the periods of bulls and bears.
The SHO oscillates between +40 and -40.
The crossover at those levels creates buy and sell signals.
In an uptrend, the SHO fluctuates between 0 and +40 where the bulls are controlling the market.
On the contrary, the SHO fluctuates between 0 and -40 during downtrends where the bears controlthe market.
Reaching the extreme level -60 in an uptrend is a sign of weakness.
Force Index with Buy on Dip strategyThis charts has 2 indicators
1 - Force Index
This indicator is based on Dr Alexander Elder ForceIndex indicator with relate price to volume by multiplying net change and volume.
- GREEN Bar indicates Bull is in control
- RED Bar indicates Bear is in control.
LENGTH of the bar indicate the strength of Bull or Bear.
Normally there's potential BUY if the RED bar turned GREEN and SELL if GREEN to RED.
2 - Stochastic momentum
Stochastic momentum is to detect potential Reversal where BLUE bar will appear if :-
- Oversold - Stochastic less than 35
- Closing price is higher than last 2 High (Fast Turtle)
// Note : Best use with "EMA Indicators with BUY sell Signal"
Hersheys Volume Pressure v1Hersheys Volume Pressure gives you very nice confirmation of trend starts and stops using volume and price.
For up bars...
If you have a large price range with low volume, that's very bullish.
If you have a small price range with low volume, that's bullish.
For down bars...
If you have a large price range with low volume, that's very bearish.
If you have a small price range with low volume, that's bearish.
Look at the chart and you'll see how trends start and end with a PINCH and widen in the middle of the moves.
Hersheys Volume Pressure is unique, in that it measures bull/bear pressure on each bar by itself. Other volume indicators like On Balnce Volume and Price Volume Trend use cumulative differences in the current and previous bar to show trends.
You can set the moving average period, 14 is the default.
Good trading!
Brian Hershey
Murrey Math Extremes ComparatorHOW IT WORKS
Creates two murrey math oscillators (hidden) one with 256 length another with 32 length and compare each other.
WHAT GIVE ME THIS SCRIPT
The script can give you very valuable information:
- Main Trend
- Pullbacks detections
- Extreme overbought oversold prices alerts
- Divergences
- Any timeframe usage
REFERENCES OF USAGE
Main Trend Indications
****The main trend is indicated with green(bull) or red(bears) small "triangles" on the bottom(bull) or the top(bears) of the chart.
*****To detect the Bull/Bear major trend the script use 256 murrey, if > 0 (green) we are uptrend in other cases we are downtrend
Pullback detection
****The pullbacks are indicated with Green(bull) or red(bears) medium "Arrows"
*****To detect pullbacks the system compare the long term murrey with the short term murrey, if long term is Green(green triangles)
*****so we are in a main bull trend, if the short term murrey make an extreme low then the pullback is indicated
*****The same for the short pullback, if long term murrey is RED and we have an extreme green short term murrey we shot a red arrow
Extreme Overbught/Oversold
****The extreme OO is indicated with fancy diamonds
*****To detect the Extremes price movements we combine the two murrey, if Long Term Murrey is overbought and short term murrey too
*****Then the diamond show on the screen obove or below based on the extreme if overbought or oversold
Strategy Resume:
Triangles indicate Major Trend Up/Down
Arrows Indicate Continuation pullbacks
Diamonds Indicate Extreme Prices
GUIDE HOW TO IMAGES
How it's works Behind Scene
Indicators: Volume-Weighted MACD Histogram & Sentiment Zone OscVolume-Weighted MACD Histogram
-------------------------------------------------------------------------------------
Volume-Weighted MACD Histogram, first discussed by Buff Dormeier, is a modified version of MACD study. It calculates volume-averaged Close price for finding the histogram.
More info:
www.moneyshow.com
Sentiment Zone Oscillator
-------------------------------------------------------------------------------------
Sentiment Zone Oscillator, developed by Walid Khalil, is a complementing oscillator to VZO and PZO.
To quote Walid:
>> The sentiment zone oscillator (SZO) is a leading contrary oscillator that measures the extreme emotions of a single market or share.
>> It measures and defines both extremes, bullishness (overoptimism) and bearishness (overpessimism), that could lead to a change
>> in sentiment, eventually changing the trend of the time frame under study. The SZO was devised on the belief that after several waves
>> of rising prices, investors begin to get bullish on the stock with increasing confidence since the price has been rising for some time.
>> The SZO measures that bullishness/bearishness and marks overbought/oversold levels.
SZO has its own oversold/overbought bands. Also, when SZO goes above 7, it indicates extreme optimism. When the SZO goes below -7, it indicates extreme pessimism.
More info: www.traders.com
How to import / use custom indicators from this chart?
-------------------------------------------------------------------------------------
PDF: drive.google.com
OBV WaveTrend Pressure OBV WaveTrend Pressure — A Volume-Powered Momentum Oscillator
OBV WaveTrend Pressure combines Hybrid OBV (volume × price delta) with the classic LazyBear WaveTrend framework to create a volume-weighted momentum oscillator that highlights real buying/selling pressure before price reacts.
While standard WaveTrend uses price averages alone, this tool feeds a cumulative hybrid OBV source into WT1/WT2, producing a much more sensitive, order-flow-aware momentum signal. The result is a clean, MACD-style histogram built from the slope of WT1, revealing when volume-backed momentum flips from bullish to bearish and vice-versa.
This is designed as a companion to volatility tools (e.g., TTM Squeeze, SQZMOM) and standard price-based WaveTrend indicators.
⸻
Features
1. Hybrid OBV Source (Vol × ΔPrice)
Captures true directional volume pressure, giving earlier and more reliable inflection points than price-based oscillators.
2. WaveTrend Applied to OBV
Applies LazyBear’s WT logic to a volume-driven source:
• WT1 (fast)
• WT2 (signal)
• Optional slope-aware color themes
3. MACD-Style Pressure Histogram
Shows momentum contraction/expansion clearly:
• Bright green/blue → Strong bull pressure
• Pale green/blue → Weakening bull
• Bright red → Strong bear pressure
• Pale red → Weakening bear
4. Dynamic OB/OS Bands
Adaptive overbought/oversold computed from:
• Rolling mean of WT1
• Rolling standard deviation
Helps identify exhaustion relative to market conditions, not fixed numbers.
5. Zero-Line Momentum Flips (with alerts)
Alerts fire when:
• WT1 slope crosses above zero → Bull momentum shift
• WT1 slope crosses below zero → Bear momentum shift
6. Optional Price Bar Coloring
Mirror the histogram state onto price bars for fast visual bias confirmation.
⸻
How to Use
Bullish Signals
• Histogram flips positive
• WT1 rising
• WT1 or WT2 near dynamic oversold zone
• Useful for positioning early in momentum cycles
Bearish Signals
• Histogram flips negative
• WT1 falling
• WT1 or WT2 near dynamic overbought zone
Best Applications
• Trend continuation entries
• Confirming TTM squeeze setups
• Early identification of pressure reversals
• Pairing with price-based WaveTrend for dual confirmation
⸻
Why It Works
WaveTrend is already one of the most reliable oscillators for structure and reversals — but this version feeds it volume pressure instead of price.
Volume often shifts before candles do, making this a leading indicator in many cases.
⸻
Credits
• WaveTrend algorithm from LazyBear
• Hybrid OBV concept extended and modernized for this release
• Completely rebuilt on Pine v6
⸻
Support & Donations
I’m an independent developer and all my indicators are written, tested, and maintained solo.
If this tool helped your trading, consider supporting development:
Support the Developer
I’m a solo independent developer and build all my tools entirely on my own time.
If this indicator helped you, consider supporting future development:
⚡ Bitcoin Lightning (Strike — preferred):
stuartbill@strike.me
₿ Bitcoin (on-chain):
BC1Q3GVF3NSGVFN24SW2DCXX2RPEY47XA2ECGEW55Y
Ξ Ethereum:
0x7226361178d820418d648ffEec61E8e1dedCe39F
◎ Solana:
C9eYYQLgzsjPSW7Mo2BXPsXz5LZhuJZTb7XuZM3hQhH1
Thank you for supporting independent creators.
Hyper Squeeze Sniper (Dual Side: Long + Short)Hyper Squeeze Sniper (Dual Side: Long + Short)
Tagline: A professional-grade volatility breakout system designed to catch explosive moves in both Bull and Bear markets.
Description
The Hyper Squeeze Sniper is a comprehensive momentum indicator that combines Volatility Analysis, Volume Spread Analysis, and Trend Following logic into a single system. It is designed to identify the "Squeeze" (consolidation phase) and signal high-probability entries exactly when the price explodes.
This script features a built-in State Machine to manage trade status (Wait, Long, Short) and prevent conflicting signals.
🛠 Concepts & Calculations (The Logic)
This indicator uses a 3-step validation process to generate signals:
1. The Squeeze Detection (Consolidation)
Before a trend explodes, volatility usually contracts. We measure this using the relationship between Bollinger Bands (BB) and Keltner Channels (KC).
Logic: When the Bollinger Bands (Length 20, Mult 2.0) narrow completely inside the Keltner Channels (Length 20, Mult 1.5), the background turns Gray.
Meaning: Energy is building up. This is a "No Trade" zone.
2. The Breakout & Confirmation (Entry)
We do not trade every breakout. The script filters for "Smart Money" moves using:
Momentum Filter: Uses Linear Regression (20 periods) to calculate the true slope of the price. We only go Long if the slope is Positive, and Short if Negative.
Volume Filter: The breakout candle must have a volume at least 1.2x higher than the 20-period average (vol_mult = 1.2). This filters out fake breakouts with low participation.
Price Action: The candle must close in the direction of the trend (Green for Long, Red for Short).
3. The Trailing Stop (Risk Management)
Once a position is taken, an ATR Trailing Stop (Chandelier Exit logic) is activated.
Calculation: It uses a 14-period ATR with a multiplier of 3.0.
Behavior: The stop line only moves in favor of the trade (Ratcheting effect) to lock in profits as the trend extends.
📊 How to Use
For LONG Setups (Bullish)
Wait: Look for the Gray Squeeze Zone.
Signal: A Green Triangle labeled "LONG" appears below the bar.
Hold: Stay in the trade as long as the price remains ABOVE the Green Safety Line.
Exit: Close the position when the 'X' mark appears (Price closes below the Green Line).
For SHORT Setups (Bearish)
Wait: Look for the Gray Squeeze Zone.
Signal: A Red Triangle labeled "SHORT" appears above the bar.
Hold: Stay in the trade as long as the price remains BELOW the Orange Safety Line.
Exit: Close the position when the 'X' mark appears (Price closes above the Orange Line).
⚙️ Settings (Default)
Squeeze Settings: BB (20, 2.0) / KC (20, 1.5).
Volume Filter: 1.2 (Requires 20% higher volume than average).
ATR Exit: 3.0 (Wide stop for capturing large trends).
🖥 Dashboard
A status table is located at the top-right corner to provide real-time data:
Trend: Shows the current market phase (Squeeze, Bullish, or Bearish).
Status: Displays the current signal state (LONG, SHORT, or WAIT).
Stop Loss: Displays the precise price level for the trailing stop.
Liquidity Structure & Sweeps [Visualized]Liquidity Structure & Sweeps | 流动性结构与猎杀
1. Design Philosophy & Logic
This indicator is designed based on Smart Money Concepts (SMC) and Market Microstructure principles. Unlike traditional indicators that rely on lagging averages or repainting fractals, this script focuses on "Objective Structure" and "Liquidity Grabs".
The core design philosophy rests on three pillars:
Zero Repainting (Real-time Integrity): We utilize a strict "Left-Side Confirmation" algorithm. A structure level is only stored in memory when the candle is fully closed (barstate.isconfirmed). This ensures that the historical signals you see are exactly what happened in real-time.
Institutional Memory (Visualized): Markets "remember" key levels. This script draws dashed lines extending from valid pivot points. These lines represent "resting liquidity" (Stop Orders). They remain on the chart until the price interacts with them.
Sweep vs. Breakout: Not all breaches are equal. We specifically look for "Sweeps" (Liquidity Grabs) — where price pierces a level but closes back inside. This is a classic sign of absorption and potential reversal, distinct from a structural breakout.
2. Key Features
Visualized Order Blocks: Automatically draws potential support (Green Dotted) and resistance (Red Dotted) lines based on fractal points.
Wick Detection: Filters out strong momentum breakouts. Signals are only generated when a specific "Wick Ratio" is met, indicating a rejection.
Clean Charts: Features a "Garbage Collection" mechanism. Once a level is swept, the line is removed, and a signal dot is placed. Old, untouched levels are automatically cycled out to prevent chart clutter.
3. How to Use
The Lines (Context):
Red Dotted Line: Buy-side Liquidity (Resistance). Expect potential shorts or breakouts here.
Green Dotted Line: Sell-side Liquidity (Support). Expect potential longs or breakdowns here.
The Signals (Action):
Red Dot (Bearish Sweep): Price spiked above a Resistance Line but closed below it. This suggests long stops were hunted, and bears are stepping in.
Green Dot (Bullish Sweep): Price spiked below a Support Line but closed above it. This suggests short stops were hunted, and bulls are stepping in.
Configuration:
Structure Length: Adjusts sensitivity. Higher values (e.g., 20-50) find major swing points; lower values (e.g., 5-10) find scalping setups.
Wick Filter %: The minimum size of the wick relative to the breakout. Increase this to filter for only the most dramatic rejections.
4. Developer Notes & Considerations
Why do lines disappear? In this logic, liquidity is treated as "Fuel". Once a level is swept (the stop orders are triggered), the fuel is consumed. Keeping the line would clutter the chart with invalid data.
Why is the dot small? The indicator is designed to be part of a toolchain, not a standalone signal. The minimalist design prevents visual interference with price action or other indicators.
1. 设计思路与核心逻辑
本指标基于 聪明钱概念 (SMC) 与 市场微观结构 原理设计。不同于依赖滞后均线或存在重绘问题的传统分形指标,本脚本专注于捕捉 “客观结构” 与 “流动性猎杀 (Liquidity Grabs)”。
核心设计哲学包含三大支柱:
零重绘 (Zero Repainting): 我们采用了严格的“左侧确认”算法。所有的结构位仅在K线完全收盘 (barstate.isconfirmed) 后才会被记录。这保证了您回测看到的信号与实盘完全一致,杜绝“未来函数”陷阱。
可视化的机构记忆: 市场是有记忆的。本脚本会从有效的波段高低点引出虚线。这些虚线代表了“沉睡的流动性”(止损盘聚集区)。它们会一直延伸,直到价格触碰它们。
区分“猎杀”与“突破”: 并不是所有的破位都是一样的。我们专注于识别“扫损(Sweep)”——即价格刺破了关键位,但收盘价收回了关键位内部。这是典型的吸筹或派发信号,与趋势延续的真突破有本质区别。
2. 主要功能
结构可视化: 自动基于分形点绘制潜在的支撑线(绿色虚线)和阻力线(红色虚线)。
插针检测: 过滤掉强势的实体突破。只有当价格出现明显的“长影线”拒绝行为时,才会触发信号。
图表自清洁: 内置“垃圾回收”机制。一旦某个关键位的流动性被猎杀(触发信号),该线条会被自动删除。过旧且未被触碰的线条也会被自动替换,保持图表整洁。
3. 使用指南
线条 (市场语境):
红色虚线: 买方流动性池(阻力位)。
绿色虚线: 卖方流动性池(支撑位)。
信号点 (交易动作):
红色圆点 (看跌猎杀): 价格刺破了红色阻力线,但收盘价回落到线下方。这暗示多头止损被触发,主力可能正在建立空单。
绿色圆点 (看涨猎杀): 价格刺破了绿色支撑线,但收盘价反弹到线上方。这暗示空头止损被触发,主力可能正在建立多单。
参数设置建议:
Structure Length (结构周期): 调整灵敏度。数值越大(如 20-50)锁定大级别波段;数值越小(如 5-10)适合短线剥头皮。
Wick Filter % (影线过滤): 设置影线占价格波动的最小比例。调大该数值可以只看最剧烈的反转信号。
4. 开发者注记与潜在考量
为什么线条会消失? 在本逻辑中,流动性被视为“燃料”。一旦发生猎杀(止损单成交),该位置的燃料即被消耗。移除线条是为了防止无效数据干扰判断。
为什么圆点设计得很小? 该指标旨在成为您交易工具链的一部分,而非唯一的决策依据。极简设计是为了避免干扰裸K形态或其他指标的观察。
===============================================================
这个脚本(我们称之为 Liq Structure Script)本质上是一个基于价格行为(Price Action)的结构猎杀探测器。
以下是详细的深度对比分析:
1. 如何使用? (实战操作手册)
不要把它当作“红灯停绿灯行”的傻瓜指标。把它当作一个**“战场地图”**。
第一阶段:观察结构 (The Setup)
图表上会自动画出 红色虚线(上方压力)和 绿色虚线(下方支撑)。
解读:告诉自己,“这里埋着很多人的止损单”。不要在这里盲目追涨杀跌。
第二阶段:等待猎杀 (The Trigger)
耐心等待价格冲向这些虚线。
关键动作:价格刺破虚线,然后迅速收回。
信号确认:虚线消失,留下一个 红点(顶部猎杀)或 绿点(底部猎杀)。
第三阶段:进场逻辑 (The Execution)
做空逻辑:出现红点 + K线留长上影线 → 说明多头试图突破失败,被主力“倒了一盆冷水”。此时可尝试做空,止损设在刚刚那个最高点上方一点点。
做多逻辑:出现绿点 + K线留长下影线 → 说明空头试图砸盘失败,被主力接住了。
传统爆量是“燃料”,Liq 脚本是“引爆点”。没有引爆点的爆量可能是空转;没有爆量的引爆点可能是假摔。Liq 脚本是一个免费、轻量级、基于K线逻辑的替代品。它不需要你买昂贵的数据服务,它利用的是“图表形态学”中的流动性共识。
结论:如何定位这个工具?
这个脚本不是“预测未来的水晶球”,而是一个**“高胜率区域提示器”**。
用它来找位置(哪里有陷阱?)。
用成交量来做确认(是不是真的有主力介入?)。
用宏观逻辑来定方向(现在该做多还是做空?)。
它是你交易工具链中负责**“微观入场时机(Timing)”**的那一环。
Momentum Day Trading ToolkitMomentum Day Trading Toolkit
Complete User Guide
Table of Contents
Overview
Quick Start
The Dashboard
Module 1: 5 Pillars Screener
Module 2: Gap & Go
Module 3: Bull Flag / Flat Top
Module 4: Float Rotation
Module 5: R2G / G2R
Module 6: Micro Pullback
Signal Reference
Quality Score
Settings Guide
Alerts Setup
Trading Workflows
Troubleshooting
Overview
The Momentum Day Trading Toolkit combines 6 powerful indicators into one unified system for day trading momentum stocks.
ModulePurpose① 5 PillarsConfirms stock is "in play"② Gap & GoPre-market levels & gap analysis③ Bull Flag / Flat TopClassic breakout patterns④ Float RotationMeasures true interest level⑤ R2G / G2RTracks prior close crosses⑥ Micro PullbackPrecision continuation entries
All modules work together - the dashboard shows you everything at a glance, and you can enable/disable any module you don't need.
Quick Start
Step 1: Add to Chart
Add the indicator to any stock chart
Recommended timeframes: 1-minute, 5-minute, or 15-minute
Step 2: Check the Dashboard (Top Right)
Look for:
Status = Current state (Scanning, Entry Signal, etc.)
Quality Score = Setup rating out of 10
Green checkmarks (✓) = Criteria passing
Step 3: Watch for Entry Signals
Triangles, circles, diamonds below bars = Entry signals
Arrows = R2G/G2R crosses
Step 4: Set Alerts
Right-click chart → Add Alert
Select "Momentum Day Trading Toolkit"
Choose your alert condition
The Dashboard
The dashboard in the top-right corner gives you instant analysis:
┌─────────────────────────────┐
│ MOMENTUM TOOLKIT │
├─────────────────────────────┤
│ Status │ 🎯 ENTRY SIGNAL │
│ Day │ 🟢 GREEN │
│ Gap │ +8.5% 🔥 │
│ RVol │ 3.2x ✓ │
│ Rotation │ 1.45x 🔥 │
│ Float │ 5.2M 🔥 │
│ Change │ +12.3% ✓ │
│ Pattern │ BULL FLAG! │
│ EMA 9/20 │ Above Both ✓ │
│ VWAP │ Above ✓ │
│ Prior Cl │ 5.91 │
│ PM High │ 9.11 ✓ │
│ Price │ 9.46 ✓ │
└─────────────────────────────┘
Dashboard Row Reference
RowWhat It ShowsGood ValuesStatusCurrent state🎯 ENTRY SIGNALDayGreen/Red vs prior close🟢 GREENGapGap % from prior close🔥 (5%+) or 🔥🔥 (10%+)RVolRelative volume✓ (2x+) or ✓✓ (5x+)RotationFloat rotation🔥 (1x) or 🔥🔥 (2x+)FloatFloat in millions🔥 (<5M) or Low (<10M)ChangeDaily % change✓ (meets minimum)PatternPattern statusBREAKOUT!EMA 9/20Trend positionAbove Both ✓VWAPVWAP positionAbove ✓Prior CloseKey R2G levelReference pricePM HighPre-market high✓ = Above itPriceCurrent price✓ = In range
Status Messages
StatusMeaningActionScanning...Looking for setupsWait✅ ALL PILLARSStock qualifiesWatch for pattern⏳ PATTERN FORMINGSetup developingGet ready🎯 ENTRY SIGNALSignal triggeredExecute trade
Module 1: 5 Pillars Screener
What It Does
Confirms the stock meets basic criteria to be worth trading.
The 5 Pillars
PillarDefaultWhy It MattersRelative Volume2x+ (5x for "strong")Confirms unusual interestDaily Change5%+Stock is movingPrice Range$1-$20Sweet spot for momentumFloat Size<20M sharesLower float = bigger moves
Visual Indicator
Green background appears when ALL pillars pass
Dashboard Shows
Individual pillar status with ✓ checkmarks
Quality score includes pillar factors
Settings
SettingDefaultDescriptionMin RVol2.0xMinimum relative volumeStrong RVol5.0xVolume for full qualificationMin Change5%Minimum daily moveMin Price$1Minimum stock priceMax Price$20Maximum stock priceMax Float20MMaximum float size
Module 2: Gap & Go
What It Does
Analyzes pre-market gaps and displays key price levels.
Key Levels Displayed
LevelColorDescriptionPrior CloseOrangeYesterday's close - THE key levelPM HighGreenPre-market high - breakout levelPM LowRedPre-market low - support
Gap Classification
Gap SizeRatingMeaning5-9.9%🔥 QualifyingWorth watching10%+🔥🔥 StrongHigh priority
Entry Signal
Small green triangle = PM High Breakout
How to Trade
Stock gaps up in pre-market
Wait for market open
Look for break above PM High
Enter on breakout with stop below PM Low
Settings
SettingDefaultDescriptionMin Gap %5%Qualifying gap thresholdStrong Gap %10%Strong gap thresholdShow PM LevelsONDisplay PM high/low lines
Module 3: Bull Flag / Flat Top
What It Does
Detects classic continuation patterns and signals breakouts.
Bull Flag Pattern
▲ BREAKOUT (Entry Signal)
│
┌────┴────┐
│ Pullback │ ← 2-5 red candles
│ (flag) │ Max 50% retrace
└─────────┘
│
┌────┴────┐
│ Pole │ ← 3+ green candles
│ (move) │ Strong momentum
└─────────┘
Flat Top Pattern
═══════════════ Resistance (2+ touches)
│
▲ BREAKOUT above resistance
Entry Signals
SignalShapeColorPatternBull Flag Breakout▲ TriangleLimeFlag breaks upFlat Top Breakout◆ DiamondAquaResistance breaks
How to Trade Bull Flag
See 3+ green candles (the pole)
Price pulls back 2-5 red candles
Pullback stays above 50% of move
Enter on break above pullback high
Stop below pullback low
Settings
SettingDefaultDescriptionMin Pole Candles3Green candles neededMax Pullback5Max red candles allowedMax Retrace50%Max pullback depthFT Touches2Resistance touches neededFT Lookback10Bars to check for resistance
Module 4: Float Rotation
What It Does
Tracks how many times the entire float has traded hands today.
The Formula
Rotation = Cumulative Day Volume ÷ Float
Rotation Levels
RotationEmojiMeaning0.5x—Half float traded1.0x🔥FULL rotation - significant!2.0x🔥🔥Double rotation - extreme3.0x+🔥🔥🔥Triple rotation - rare event
Why It Matters
High rotation = Extreme interest
Everyone who owns shares has likely traded
Often precedes explosive moves
Shows "real" demand beyond just volume
Dashboard Shows
Current rotation level
Fire emojis for milestones
Settings
SettingDefaultDescriptionFloat SourceAutoAuto-detect or manualManual Float10MIf auto fails, use thisAlert Level1.0xAlert when rotation hits this
Module 5: R2G / G2R
What It Does
Tracks when price crosses the prior day's close - a key psychological level.
Red to Green (R2G) 🟢
Prior Close ─────────────────
↗ CROSS TO GREEN
↗
(opened red)
Stock opened below prior close (red)
Crosses above prior close (green)
BULLISH signal
Green to Red (G2R) 🔴
(opened green)
↘
↘ CROSS TO RED
Prior Close ─────────────────
Stock opened above prior close (green)
Crosses below prior close (red)
BEARISH signal
Entry Signals
SignalShapeColorMeaningR2G↑ ArrowLimeCrossed to greenG2R↓ ArrowRedCrossed to red
Why R2G Matters
Bears who shorted get squeezed
Creates FOMO buying
Prior close becomes support
Momentum often continues
Dashboard Shows
Current day status (🟢 GREEN / 🔴 RED)
Whether R2G or G2R occurred (R2G ✓ or G2R ✓)
Settings
SettingDefaultDescriptionRequire Opposite OpenONR2G needs red openShow Prior CloseONDisplay the line
Module 6: Micro Pullback
What It Does
Finds precision entries on brief 1-3 candle pullbacks after strong moves.
The Pattern
▲ ENTRY (break pullback high)
│
┌──┴───┐
│ 1-3 │ ← Micro pullback (brief!)
│ red │ Stop = low of this
└──────┘
│
┌──┴───┐
│ 3+ │ ← Strong move
│green │ Momentum building
└──────┘
Why Micro Pullbacks Work
Tight stop = Pullback low is close
Momentum intact = Only paused briefly
Early entry = Catch continuation early
Clear trigger = Break of pullback high
Entry Signal
SignalShapeColorMicro Pullback Entry● CircleYellow
How to Trade
See 3+ green candles (strong move)
1-3 red candles (brief pause)
Pullback stays above 50% retrace
Enter when green candle breaks pullback high
Stop at pullback low
Settings
SettingDefaultDescriptionMin Green Candles3Candles before pullbackMax Pullback3Max red candlesMax Retrace50%Max pullback depth
Signal Reference
All Entry Signals (Below Bar)
ShapeColorSignalModule▲ Large TriangleLimeBull Flag BreakoutPatterns◆ DiamondAquaFlat Top BreakoutPatterns● CircleYellowMicro Pullback EntryMicro PB▲ Small TriangleGreenPM High BreakoutGap & Go↑ ArrowLimeRed to GreenR2G/G2R
Warning Signals (Above Bar)
ShapeColorSignalModule↓ ArrowRedGreen to RedR2G/G2R
Optional Forming Signals (Disabled by Default)
ShapeColorSignal🚩 FlagFaded LimeBull Flag Forming● CircleFaded YellowMicro PB Forming
Enable "Show 'Forming' Markers" in settings to see these
Quality Score
The quality score (0-10) rates the overall setup strength.
Scoring Breakdown
FactorPointsRVol 5x++2RVol 2x++1Daily change 5%++1Low float (<20M)+1Strong gap (10%+)+2Qualifying gap (5%+)+1Rotation 1x++2Rotation 0.5x++1Above EMA 20+1
Score Interpretation
ScoreGradeAction8-10A+Best setups - full position6-7AGood setups - standard size4-5BAverage - reduced size0-3CWeak - skip or paper trade
Settings Guide
Module Toggles
Turn each module ON/OFF:
SettingDefaultDescription① 5 Pillars ScreenerONStock qualification② Gap & Go AnalysisONGap & level analysis③ Bull Flag / Flat TopONPattern detection④ Float RotationONRotation tracking⑤ R2G / G2R TrackerONPrior close crosses⑥ Micro PullbackONPullback entries
Visual Settings
SettingDefaultDescriptionShow DashboardONDisplay info tableTable SizeNormalSmall/Normal/LargeShow Entry SignalsONDisplay entry shapesShow 'Forming' MarkersOFFShow pattern formingShow Key LevelsONPrior close, PM levelsShow EMA 9/20ONTrend EMAsShow VWAPONVWAP line
Recommended Presets
Minimal (Clean Chart)
Show Dashboard: ON
Show Entry Signals: ON
Show 'Forming' Markers: OFF
Show Key Levels: OFF
Show EMA: OFF
Show VWAP: OFF
Standard (Balanced)
All defaults
Full Analysis
All settings ON
Alerts Setup
Available Alerts
AlertTriggerAny Bullish EntryAny entry signal firesBull Flag BreakoutBull flag breaks outFlat Top BreakoutFlat top breaks outMicro Pullback EntryMicro PB triggersPM High BreakoutBreaks above PM highRed to GreenR2G crossGreen to RedG2R crossFloat RotationHits rotation level5 Pillars PassAll pillars qualifyPattern FormingPattern starts formingHigh Quality EntryEntry with score 7+/10
How to Set Alerts
Right-click on chart
Select "Add Alert"
Condition: "Momentum Day Trading Toolkit"
Select alert type from dropdown
Set expiration and notifications
Click "Create"
Recommended Alerts
For Active Trading:
Any Bullish Entry
High Quality Entry
For Watchlist Monitoring:
5 Pillars Pass
Float Rotation
Trading Workflows
Workflow 1: Full Qualification
Step 1: 5 PILLARS
└─→ Wait for "✅ ALL PILLARS" status
Step 2: CHECK SETUP
└─→ Quality score 6+?
└─→ Above EMA and VWAP?
Step 3: WAIT FOR ENTRY
└─→ Bull Flag, Flat Top, or Micro PB signal
Step 4: EXECUTE
└─→ Enter on signal
└─→ Stop below pattern low
└─→ Target 2:1 minimum
Workflow 2: Gap & Go
Step 1: PRE-MARKET
└─→ Stock gaps 5%+ (shows in Gap row)
Step 2: MARKET OPEN
└─→ Note PM High level (green line)
Step 3: WAIT FOR BREAK
└─→ PM High Breakout signal (small triangle)
Step 4: CONFIRM
└─→ R2G if opened red (double confirmation)
└─→ RVol 2x+
Step 5: EXECUTE
└─→ Enter on PM High break
└─→ Stop below PM Low
Workflow 3: Micro Pullback Scalp
Step 1: FIND MOMENTUM
└─→ Stock moving, 3+ green candles
Step 2: WAIT FOR PAUSE
└─→ 1-3 red candles (brief pullback)
Step 3: ENTRY
└─→ Yellow circle signal appears
Step 4: QUICK TRADE
└─→ Enter at signal
└─→ Tight stop at pullback low
└─→ Quick target (1:1 to 2:1)
Troubleshooting
Q: Lines are moving/jumping on real-time chart?
A: This was fixed in latest version. Make sure you have the newest code. Lines now lock in place at market open.
Q: Too many signals, chart is cluttered?
A:
Turn off "Show 'Forming' Markers"
Disable modules you don't need
Use "Minimal" visual preset
Q: No signals appearing?
A:
Check if "Show Entry Signals" is ON
Make sure relevant module is enabled
Stock may not meet pattern criteria
Q: Dashboard shows wrong float?
A:
TradingView float data isn't available for all stocks
Switch Float Source to "Manual"
Enter correct float in millions
Q: PM High/Low not showing?
A:
Only appears during market hours
Needs pre-market data to calculate
Check if "Show Key Levels" is ON
Q: Quality score seems wrong?
A:
Score updates in real-time
Check individual factors in dashboard
RVol and rotation change throughout day
Q: Alert not triggering?
A:
Make sure alert is set on correct symbol
Check alert hasn't expired
Verify condition is set correctly
Quick Reference Card
Entry Signals
▲ Lime Triangle = Bull Flag Breakout
◆ Aqua Diamond = Flat Top Breakout
● Yellow Circle = Micro Pullback
▲ Green Triangle = PM High Break
↑ Lime Arrow = R2G (bullish)
↓ Red Arrow = G2R (bearish)
Dashboard Quick Read
🎯 = Entry signal active
✅ = All pillars pass
🟢 = Day is green
🔥 = Strong (gap/rotation)
✓ = Criteria met
✗ = Criteria failed
Quality Score
8-10 = A+ (Best)
6-7 = A (Good)
4-5 = B (Average)
0-3 = C (Weak)
Key Levels
Orange Line = Prior Close (R2G level)
Green Line = PM High (breakout level)
Red Line = PM Low (support)
Purple Line = VWAP
Yellow/Orange = EMA 9/20
Happy Trading! 🎯📈
For questions or issues, use TradingView's comment section on the indicator page.
Red to Green / Green to Red Tracker# Red to Green / Green to Red Tracker - Quick Reference
## Core Concept
```
PRIOR CLOSE = Yesterday's closing price = The "zero line" for today
Above Prior Close = 🟢 GREEN (profitable for yesterday's buyers)
Below Prior Close = 🔴 RED (losing for yesterday's buyers)
```
---
## The Two Key Moves
### 🟢 Red to Green (R2G)
```
OPEN: Below prior close (RED)
↓
CROSS: Price moves above prior close
↓
RESULT: Now GREEN - Bullish signal
```
**Why it matters:**
- Bears who shorted get squeezed
- Creates FOMO buying
- Momentum often continues
---
### 🔴 Green to Red (G2R)
```
OPEN: Above prior close (GREEN)
↓
CROSS: Price moves below prior close
↓
RESULT: Now RED - Bearish signal
```
**Why it matters:**
- Longs who bought get trapped
- Triggers stop losses
- Panic selling follows
---
## Signals Explained
| Signal | Shape | Location | Meaning |
|--------|-------|----------|---------|
| R2G | ▲ Green Triangle | Below bar | Crossed to green |
| G2R | ▼ Red Triangle | Above bar | Crossed to red |
---
## Level Lines
| Line | Color | Style | What It Is |
|------|-------|-------|------------|
| Prior Close | Orange | Solid | KEY R2G/G2R level |
| Prior High | Green | Dashed | Yesterday's high |
| Prior Low | Red | Dashed | Yesterday's low |
| Today Open | White | Dotted | Gap reference |
---
## Info Table Reference
| Field | What It Shows |
|-------|---------------|
| Status | 🟢 GREEN / 🔴 RED / ⚪ FLAT |
| Day Change | % change from prior close |
| Prior Close | The key level price |
| Distance | How far from prior close |
| Opened | Did today open green or red |
| R2G | R2G status + price if triggered |
| G2R | G2R status + price if triggered |
| Rel Vol | Current relative volume |
| Prior High | Yesterday's high + distance |
| Prior Low | Yesterday's low + distance |
---
## Trading R2G (Long Setup)
### Entry Checklist
- Stock opened RED (below prior close)
- R2G cross signal triggered (green triangle)
- Volume confirmation (1.5x+ preferred, 2x+ ideal)
- Price holding above prior close
- Overall market not tanking
### Entry Method
1. **Aggressive:** Enter immediately on R2G cross
2. **Conservative:** Wait for pullback to prior close (now support)
### Stop Loss
- Below the R2G cross candle low
- OR below prior close (tighter)
### Target
- Prior day high (first target)
- 2:1 risk-reward minimum
---
## Trading G2R (Short Setup)
### Entry Checklist
- Stock opened GREEN (above prior close)
- G2R cross signal triggered (red triangle)
- Volume confirmation
- Price staying below prior close
- Overall market not ripping
### Entry Method
1. **Aggressive:** Enter immediately on G2R cross
2. **Conservative:** Wait for bounce to prior close (now resistance)
### Stop Loss
- Above the G2R cross candle high
- OR above prior close (tighter)
### Target
- Prior day low (first target)
- Gap fill (if gapped up)
---
## Signal Quality
### High Quality R2G ✓
- Opened significantly red (-2% or more)
- Strong volume on cross (2x+)
- First R2G of the day
- Market trending up
- News catalyst present
### Low Quality R2G ✗
- Opened barely red (-0.5%)
- Low volume cross
- Multiple R2G/G2R already today (choppy)
- Fighting market direction
- No clear catalyst
---
## Common Patterns
### Clean R2G (Best)
```
Open red → Steady climb → Cross prior close → Continue higher
```
### Failed R2G (Avoid/Exit)
```
Open red → Cross to green → Immediately fail back to red
```
### Choppy R2G/G2R (Avoid)
```
Multiple crosses back and forth = Indecision, no clear direction
```
---
## First Cross Rule
**The FIRST R2G or G2R of the day is usually the most significant.**
Why?
- Catches traders off guard
- Largest reaction from market
- Sets tone for rest of day
If you miss the first cross, be more selective on subsequent crosses.
---
## Volume Guide
| Rel Volume | Quality | Action |
|------------|---------|--------|
| < 1.0x | Weak | Skip or small size |
| 1.0-1.5x | Average | Standard position |
| 1.5-2.0x | Good | Full position |
| 2.0x+ | Strong | High conviction |
---
## Settings Recommendations
### Default (Balanced)
```
Require Opposite Open: ON
Require Volume: ON (1.5x)
Candle Close Confirm: OFF
Min Cross %: 0
```
### Conservative (Fewer, Better Signals)
```
Require Opposite Open: ON
Require Volume: ON (2.0x)
Candle Close Confirm: ON
Min Cross %: 0.5
```
### Aggressive (More Signals)
```
Require Opposite Open: OFF
Require Volume: OFF
Candle Close Confirm: OFF
Min Cross %: 0
```
---
## Alert Setup
### Essential Alerts
1. **First R2G of Day** - Highest value alert
2. **R2G with Strong Volume** - High conviction
### How to Set
1. Right-click chart → Add Alert
2. Condition: R2G/G2R Tracker
3. Select alert type
4. Set notification method
---
## Combining with Other Indicators
| Indicator | How to Use |
|-----------|------------|
| **Gap & Go** | R2G on gap-down stock = strong reversal |
| **Bull Flag** | Look for bull flag after R2G confirmation |
| **Float Rotation** | R2G + high rotation = explosive potential |
| **VWAP** | R2G above VWAP = strongest setup |
---
## Common Mistakes
❌ **Chasing late R2G**
- If price is already 3-5% green, you missed the move
- Wait for pullback or next setup
❌ **Ignoring volume**
- Low volume R2G often fails
- Always check relative volume
❌ **Fighting the market**
- R2G in a tanking market often fails
- G2R in a ripping market often fails
❌ **No stop loss**
- Failed R2G can reverse hard
- Always have a defined stop
❌ **Overtrading choppy stocks**
- Multiple R2G/G2R = no clear direction
- Skip stocks that keep crossing back and forth
---
## Quick Decision Framework
```
1. Did it open opposite color? (Red for R2G, Green for G2R)
- NO → Lower probability, be cautious
- YES → Continue
2. Is volume confirming? (1.5x+ relative volume)
- NO → Skip or small size
- YES → Continue
3. Is this the first cross of the day?
- YES → Higher probability
- NO → Be more selective
4. Is market direction supportive?
- NO → Skip
- YES → Take the trade
5. Can you define risk? (Clear stop level)
- NO → Skip
- YES → Execute
```
---
## Key Takeaways
1. **Prior close is THE key level** - everyone watches it
2. **First cross matters most** - sets daily tone
3. **Volume confirms** - low volume crosses often fail
4. **Failed crosses reverse hard** - always use stops
5. **Don't overtrade choppy action** - multiple crosses = stay out
---
Happy Trading! 🟢🔴
SHAMAZZ = Smoothed Heikin Ashi + MA + ZigZagSHAMAZZ combines a Smoothed Heikin Ashi structure, two moving averages, and a smart ZigZag with labeled swings to help you read trend, momentum and market structure in one glance.
What it does
1. Smoothed Heikin Ashi
• Rebuilds candles using double-smoothed EMAs to filter noise
• Bull SHA candles show trend strength and clean pushes up
• Bear SHA candles highlight clean pushes down and pullbacks
2. Moving Averages
• MA 1 is the fast trend line, default 50 period
• MA 2 is the higher time frame trend line, default 200 period
• Price above both MAs and green SHA candles suggests bullish environment
• Price below both MAs and red SHA candles suggests bearish environment
3. ZigZag with labels
• Detects major and minor swing highs and lows
• Draws ZigZag lines with separate bull and bear colors
• Labels key swings as HH, HL, LH, LL so you see market structure clearly
• Label color and opacity are fully adjustable in settings
How to use it
1. Identify the main trend
• Check MA 2 slope and where SHA candles are relative to MA 1 and MA 2
• Long bias when SHA is mostly green and price holds above MA 1 and MA 2
• Short bias when SHA is mostly red and price holds below MA 1 and MA 2
2. Read structure with the ZigZag
• Uptrend pattern: HL then HH labels stepping upward
• Downtrend pattern: LH then LL labels stepping downward
• Structure shifts when the sequence breaks
Example: series of HH HL that suddenly prints a LL
3. Time entries
• In an uptrend
• Look for HL labels forming near or slightly under MA 1
• Wait for SHA candles to flip back to bullish and then look for entries in the direction of the trend
• In a downtrend
• Look for LH labels forming near or slightly above MA 1
• Wait for SHA candles to turn bearish again and then look for short setups
4. Filter chop and ranges
• When HH HL and LL LH labels mix and alternate in a tight zone, market is ranging
• You can avoid entries when SHA candles are small, mixed colors, and price is stuck around MA 1 and MA 2
5. Multi time frame use
• Set the indicator timeframe to a higher time frame to project higher time frame SHA and MAs on a lower chart
• Trade in the direction of the projected higher time frame trend and structure for cleaner setups
This indicator is designed as a trend and structure map: SHA shows the quality of the move, MAs show the larger direction, and the ZigZag labels show the story of highs and lows so you can enter with the trend and avoid random chop.
Dynamic Support and Resistance with Trend LinesDynamic Support and Resistance with Trend Lines (DSRTL)
1. Introduction & Methodology
The DSRTL indicator is designed to provide a multidimensional analysis of market structure. Unlike traditional tools that rely solely on price pivots, this script combines Static Volume-based Zones with Dynamic Trend Lines to evaluate the price's position relative to critical market components.
The S/R Identification Technique
Instead of standard pivot points, DSRTL utilizes Volume Analysis to highlight areas of significant trader participation:
- Strategy A:
Matrix Climax: Identifies candles within the lookback period that are near price extremes (Highs/Lows) and coincide with significant buying or selling volume.
- Strategy B:
Volume Extremes: Detects candles with the absolute highest buy/sell volumes within the selected lookback window, creating extreme volume-based S/R zones.
- Result:
This creates Support/Resistance (S/R) zones that are validated by actual market activity, not just price geometry.
Dynamic Trend Lines
To complement the static zones, the indicator employs two adaptive channel methods:
- Pivot Span: Connects recent significant pivots for a fast, reactive trend corridor.
- 5-Point Channel: Segments the lookback period into 5 parts to perform a linear regression analysis, creating a stable and statistically significant channel.
2. Volume Calculation Methodology
Accurate S/R detection requires distinguishing Buy Volume from Sell Volume. DSRTL offers two calculation modes:
- Geometry (Source File): Estimates buy/sell volume based on the Close price's position relative to the High/Low of the candle.
Note: This is an approximation that works on all plan types as it does not require intrabar data.
- Intrabar (Precise): Analyzes historical lower-timeframe data (e.g., 15S) to calculate intrabar-based volume deltas with higher precision compared to the geometric method.
Note: This offers superior accuracy. It requires access to historical intrabar data (depending on your plan limits). For the best analytical results, use this mode if available.
3. The Smart Matrix Engine (3D Analysis)
The core of DSRTL is its dashboard, powered by the "Smart Matrix Engine." This engine evaluates the current price in a multi-layer market structure context (Static Volume Zones + Dynamic Channels + Volume Metrics).:
A. S-State (Static): Where is the price relative to the Volume S/R zones?
B. D-State (Dynamic): Where is the price relative to the Trend Channels?
How to read the Matrix Map:
The dashboard displays a 5x5 grid representing 25 possible market scenarios.
- Rows (S1-S5): Represent the Static State (S1=Breakout, S3=Mid-Range, S5=Breakdown).
- Columns (D1-D5): Represent the Dynamic State (D1=Overextended Up, D3=Neutral, D5=Overextended Down).
- Active Cell: Marked with a dot, indicating the specific intersection of price action and market structure.
4. Matrix Interpretations (The 25 Scenarios)
Below is the detailed logic for every possible state displayed on the dashboard, explaining the Title, Bias, and actionable Signal.
Section I: S1 - Static Breakout (Price > Static Resistance)
The price has cleared the static volume resistance zone.
- S1 / D1: HYPER EXTENSION
Bias: Extreme Bullish
Signal: Caution: Exhaustion Risk. Trail stops tight.
- S1 / D2: RESISTANCE CLASH
Bias: Bullish
Signal: Breakout confirmed but facing immediate dynamic resistance.
- S1 / D3: CHANNEL BREAKOUT
Bias: Strong Bullish
Signal: Ideal Trend Continuation. Look to buy dips.
- S1 / D4: SMART PULLBACK
Bias: Bullish (Pullback)
Signal: A pullback occurring after a breakout. Strong buy opportunity.
- S1 / D5: CONFLICT (DIV)
Bias: Conflict/Reversal
Signal: Major Divergence. Static breakout is failing against dynamic structure. High Risk.
Section II: S2 - Inside Static Resistance
The price is currently testing the overhead resistance zone.
- S2 / D1: WEAK SPIKE
Bias: Neutral/Bullish
Signal: Testing resistance, but short-term overextended.
- S2 / D2: IRON FORTRESS (R)
Bias: Rejection Risk
Signal: Double Resistance (Static + Dynamic). High probability of rejection.
- S2 / D3: TESTING RES
Bias: Neutral
Signal: Consolidating at resistance. Wait for a clear break or rejection.
- S2 / D4: COMPRESSION (UP)
Bias: Conflict (Squeeze)
Signal: Squeezed between Static Resistance and Dynamic Support. Volatility imminent.
- S2 / D5: RES vs DOWN-TREND
Bias: Bearish
Signal: Strong downtrend meeting static resistance. Potential Short entry.
Section III: S3 - Mid-Range
The price is floating between significant Static Support and Resistance.
- S3 / D1: OVERBOUGHT RANGE
Bias: Rejection Risk (OB)
Signal: Overextended within the range. Potential fade (short).
- S3 / D2: RANGE HIGH LIMIT
Bias: Neutral/Bearish
Signal: At the top of the dynamic channel. Look for rejection signs.
- S3 / D3: NEUTRAL / CHOPPY
Bias: Neutral
Signal: Dead Center. Low probability environment. Avoid trading.
- S3 / D4: RANGE DIP BUY
Bias: Neutral/Bullish
Signal: At the bottom of the dynamic channel. Look for bounce signs.
- S3 / D5: WEAK RANGE (OS)
Bias: Bounce Risk (OS)
Signal: Oversold within the range. Potential fade (long).
Section IV: S4 - Inside Static Support
The price is currently testing the floor support zone.
- S4 / D1: SUP vs UP-TREND
Bias: Bullish
Signal: Strong uptrend meeting static support. Potential Long entry.
- S4 / D2: COMPRESSION (DN)
Bias: Conflict (Squeeze)
Signal: Squeezed between Static Support and Dynamic Resistance. Volatility imminent.
- S4 / D3: TESTING SUPPORT
Bias: Neutral
Signal: Consolidating at support. Wait for a bounce or breakdown.
- S4 / D4: IRON FLOOR (S)
Bias: Bounce Risk
Signal: Double Support (Static + Dynamic). High probability of a bounce.
- S4 / D5: WEAK DIP
Bias: Neutral/Bearish
Signal: Testing support, but short-term oversold.
Section V: S5 - Static Breakdown (Price < Static Support)
The price has dropped below the static volume support zone.
- S5 / D1: CONFLICT (DIV)
Bias: Conflict/Reversal
Signal: Major Divergence. Static breakdown is failing. High Risk.
- S5 / D2: BEAR PULLBACK
Bias: Bearish (Pullback)
Signal: A pullback occurring after a breakdown. Strong selling opportunity.
- S5 / D3: CHANNEL BREAKDOWN
Bias: Strong Bearish
Signal: Ideal Trend Continuation (Down). Sell rallies.
- S5 / D4: SUPPORT CLASH
Bias: Bearish
Signal: Breakdown confirmed but facing immediate dynamic support.
- S5 / D5: HYPER DROP (VOID)
Bias: Extreme Bearish
Signal: Caution: Climax risk. Trail stops for shorts.
DISCLAIMER & EDUCATIONAL PURPOSE
This indicator is strictly an educational tool designed to visualize complex market structure concepts. Its primary purpose is to help traders "bridge the gap" between academic theory and real-time market behavior by providing a visual representation of support, resistance, and volume dynamics.
Please Note:
1. Not a Trading Strategy: This script is an analytical assistant, not a standalone "Black Box" trading system. It does not generate buy or sell signals that should be followed blindly.
2. No Financial Advice: The data provided by this tool is for informational purposes only. It is not a recommendation to buy or sell any asset.
3. Risk Warning: Trading involves significant risk. Always use your own judgment, perform your own technical analysis, and use proper risk management. Do not use this tool as the sole basis for your trading decisions.
4. Data Precision & Platform Limits: The "Intrabar (Precise)" calculation mode relies on high-resolution historical data to provide exact results. Access to this specific data depth depends entirely on your platform's subscription capabilities. If your plan does not support this level of historical intrabar data, the Precise mode may have limited coverage. In that case, you should switch to "Geometry" mode for a fully populated view.
Filter Volume1. Indicator Name
Filter Volume
2. One-line Introduction
A regression-based trend filter that quantifies and visualizes market direction and strength using price behavior.
3. Overall Description
Filter Volume+ is a trend-detection indicator that uses linear regression to evaluate the dominant direction of price movement over a given period.
It compares historical regression values to determine whether the market is in a bullish, bearish, or neutral state.
The indicator applies a percentage threshold to filter out weak or indecisive trends, highlighting only significant movements.
Each trend state is visualized through distinct colors: bullish (greenish), bearish (reddish), and neutral (gray), with intensity reflecting trend strength.
To reduce noise and create smooth visual signals, a three-step smoothing process is applied to the raw trend intensity.
Users can customize the regression source, lookback period, and sensitivity, allowing the indicator to adapt to various assets and timeframes.
This tool is especially useful in filtering entry signals based on clear directional bias, making it suitable for trend-following or confirmation strategies.
4. Key Benefits (Title + Description)
✅ Quantified Trend Strength
Only displays trend signals when a statistically significant direction is detected using linear regression comparisons.
✅ Visual Clarity with Color Coding
Each market state (bullish, bearish, neutral) is represented with distinct colors and transparency, enabling fast interpretation.
✅ Custom Regression Source
Users can define the data input (e.g., close, open, indicator output) for regression calculation, increasing strategic flexibility.
✅ Multi-Level Smoothing
Applies three layers of smoothing (via moving averages) to eliminate noise and produce a stable, flowing trend curve.
✅ Area Fill Visualization
Plots a colored band between the trend value and zero-line, helping users quickly gauge the market's dominant force.
✅ Adjustable Sensitivity Settings
Includes tolerance and lookback controls, allowing traders to fine-tune how reactive or conservative the trend detection should be.
5. Indicator User Guide
📌 Basic Concept
Filter Volume+ assesses the direction of price by comparing regression values over a selected period.
If the percentage of upward comparisons exceeds a threshold, a bullish state is shown; if downward comparisons dominate, it shows a bearish state.
⚙️ Settings Overview
Lookback Period (n): The number of bars to compare for trend analysis
Range Tolerance (%): Minimum threshold for declaring a strong trend
Regression Source: The data used for regression (e.g., close, open)
Linear Regression Length: Number of bars used to compute each regression value
Bull/Bear Color: Custom colors for bullish and bearish trends
📈 Example Timing
When the trend line stays above zero and the green color intensity increases → trend gaining strength
After a neutral phase (gray), the color shifts quickly to greenish → early trend reversal
📉 Example Timing
When the trend line stays below zero with deepening red color → strong bearish continuation
Sudden change from bullish to bearish color with rising intensity
🧪 Recommended Use
Use as a trend confirmation filter alongside entry/exit strategies
Ideal for swing or position trades in trending markets
Combine with oscillators like RSI or MACD for improved signal validation
🔒 Cautions
In ranging (sideways) markets, the color may change frequently – avoid relying solely on this indicator in those zones.
Low-intensity colors (faded) suggest weak trends – better to stay on the sidelines.
A short lookback period may cause over-sensitivity and false signals.
When using non-price regression sources, expect the indicator to behave differently – test before deploying.
+++
Dynamic Equity Allocation Model//@version=6
indicator('Dynamic Equity Allocation Model', shorttitle = 'DEAM', overlay = false, precision = 1, scale = scale.right, max_bars_back = 500)
// DYNAMIC EQUITY ALLOCATION MODEL
// Quantitative framework for dynamic portfolio allocation between stocks and cash.
// Analyzes five dimensions: market regime, risk metrics, valuation, sentiment,
// and macro conditions to generate allocation recommendations (0-100% equity).
//
// Uses real-time data from TradingView including fundamentals (P/E, ROE, ERP),
// volatility indicators (VIX), credit spreads, yield curves, and market structure.
// INPUT PARAMETERS
group1 = 'Model Configuration'
model_type = input.string('Adaptive', 'Allocation Model Type', options = , group = group1, tooltip = 'Conservative: Slower to increase equity, Aggressive: Faster allocation changes, Adaptive: Dynamic based on regime')
use_crisis_detection = input.bool(true, 'Enable Crisis Detection System', group = group1, tooltip = 'Automatic detection and response to crisis conditions')
use_regime_model = input.bool(true, 'Use Market Regime Detection', group = group1, tooltip = 'Identify Bull/Bear/Crisis regimes for dynamic allocation')
group2 = 'Portfolio Risk Management'
target_portfolio_volatility = input.float(12.0, 'Target Portfolio Volatility (%)', minval = 3, maxval = 20, step = 0.5, group = group2, tooltip = 'Target portfolio volatility (Cash reduces volatility: 50% Equity = ~10% vol, 100% Equity = ~20% vol)')
max_portfolio_drawdown = input.float(15.0, 'Maximum Portfolio Drawdown (%)', minval = 5, maxval = 35, step = 2.5, group = group2, tooltip = 'Maximum acceptable PORTFOLIO drawdown (not market drawdown - portfolio with cash has lower drawdown)')
enable_portfolio_risk_scaling = input.bool(true, 'Enable Portfolio Risk Scaling', group = group2, tooltip = 'Scale allocation based on actual portfolio risk characteristics (recommended)')
risk_lookback = input.int(252, 'Risk Calculation Period (Days)', minval = 60, maxval = 504, group = group2, tooltip = 'Period for calculating volatility and risk metrics')
group3 = 'Component Weights (Total = 100%)'
w_regime = input.float(35.0, 'Market Regime Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_risk = input.float(25.0, 'Risk Metrics Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_valuation = input.float(20.0, 'Valuation Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_sentiment = input.float(15.0, 'Sentiment Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
w_macro = input.float(5.0, 'Macro Weight (%)', minval = 0, maxval = 100, step = 5, group = group3)
group4 = 'Crisis Detection Thresholds'
crisis_vix_threshold = input.float(40, 'Crisis VIX Level', minval = 30, maxval = 80, group = group4, tooltip = 'VIX level indicating crisis conditions (COVID peaked at 82)')
crisis_drawdown_threshold = input.float(15, 'Crisis Drawdown Threshold (%)', minval = 10, maxval = 30, group = group4, tooltip = 'Market drawdown indicating crisis conditions')
crisis_credit_spread = input.float(500, 'Crisis Credit Spread (bps)', minval = 300, maxval = 1000, group = group4, tooltip = 'High yield spread indicating crisis conditions')
group5 = 'Display Settings'
show_components = input.bool(false, 'Show Component Breakdown', group = group5, tooltip = 'Display individual component analysis lines')
show_regime_background = input.bool(true, 'Show Dynamic Background', group = group5, tooltip = 'Color background based on allocation signals')
show_reference_lines = input.bool(false, 'Show Reference Lines', group = group5, tooltip = 'Display allocation percentage reference lines')
show_dashboard = input.bool(true, 'Show Analytics Dashboard', group = group5, tooltip = 'Display comprehensive analytics table')
show_confidence_bands = input.bool(false, 'Show Confidence Bands', group = group5, tooltip = 'Display uncertainty quantification bands')
smoothing_period = input.int(3, 'Smoothing Period', minval = 1, maxval = 10, group = group5, tooltip = 'Smoothing to reduce allocation noise')
background_intensity = input.int(95, 'Background Intensity (%)', minval = 90, maxval = 99, group = group5, tooltip = 'Higher values = more transparent background')
// Styling Options
color_scheme = input.string('EdgeTools', 'Color Theme', options = , group = 'Appearance', tooltip = 'Professional color themes')
use_dark_mode = input.bool(true, 'Optimize for Dark Theme', group = 'Appearance')
main_line_width = input.int(3, 'Main Line Width', minval = 1, maxval = 5, group = 'Appearance')
// DATA RETRIEVAL
// Market Data
sp500 = request.security('SPY', timeframe.period, close)
sp500_high = request.security('SPY', timeframe.period, high)
sp500_low = request.security('SPY', timeframe.period, low)
sp500_volume = request.security('SPY', timeframe.period, volume)
// Volatility Indicators
vix = request.security('VIX', timeframe.period, close)
vix9d = request.security('VIX9D', timeframe.period, close)
vxn = request.security('VXN', timeframe.period, close)
// Fixed Income and Credit
us2y = request.security('US02Y', timeframe.period, close)
us10y = request.security('US10Y', timeframe.period, close)
us3m = request.security('US03MY', timeframe.period, close)
hyg = request.security('HYG', timeframe.period, close)
lqd = request.security('LQD', timeframe.period, close)
tlt = request.security('TLT', timeframe.period, close)
// Safe Haven Assets
gold = request.security('GLD', timeframe.period, close)
usd = request.security('DXY', timeframe.period, close)
yen = request.security('JPYUSD', timeframe.period, close)
// Financial data with fallback values
get_financial_data(symbol, fin_id, period, fallback) =>
data = request.financial(symbol, fin_id, period, ignore_invalid_symbol = true)
na(data) ? fallback : data
// SPY fundamental metrics
spy_earnings_per_share = get_financial_data('AMEX:SPY', 'EARNINGS_PER_SHARE_BASIC', 'TTM', 20.0)
spy_operating_earnings_yield = get_financial_data('AMEX:SPY', 'OPERATING_EARNINGS_YIELD', 'FY', 4.5)
spy_dividend_yield = get_financial_data('AMEX:SPY', 'DIVIDENDS_YIELD', 'FY', 1.8)
spy_buyback_yield = get_financial_data('AMEX:SPY', 'BUYBACK_YIELD', 'FY', 2.0)
spy_net_margin = get_financial_data('AMEX:SPY', 'NET_MARGIN', 'TTM', 12.0)
spy_debt_to_equity = get_financial_data('AMEX:SPY', 'DEBT_TO_EQUITY', 'FY', 0.5)
spy_return_on_equity = get_financial_data('AMEX:SPY', 'RETURN_ON_EQUITY', 'FY', 15.0)
spy_free_cash_flow = get_financial_data('AMEX:SPY', 'FREE_CASH_FLOW', 'TTM', 100000000)
spy_ebitda = get_financial_data('AMEX:SPY', 'EBITDA', 'TTM', 200000000)
spy_pe_forward = get_financial_data('AMEX:SPY', 'PRICE_EARNINGS_FORWARD', 'FY', 18.0)
spy_total_debt = get_financial_data('AMEX:SPY', 'TOTAL_DEBT', 'FY', 500000000)
spy_total_equity = get_financial_data('AMEX:SPY', 'TOTAL_EQUITY', 'FY', 1000000000)
spy_enterprise_value = get_financial_data('AMEX:SPY', 'ENTERPRISE_VALUE', 'FY', 30000000000)
spy_revenue_growth = get_financial_data('AMEX:SPY', 'REVENUE_ONE_YEAR_GROWTH', 'TTM', 5.0)
// Market Breadth Indicators
nya = request.security('NYA', timeframe.period, close)
rut = request.security('IWM', timeframe.period, close)
// Sector Performance
xlk = request.security('XLK', timeframe.period, close)
xlu = request.security('XLU', timeframe.period, close)
xlf = request.security('XLF', timeframe.period, close)
// MARKET REGIME DETECTION
// Calculate Market Trend
sma_20 = ta.sma(sp500, 20)
sma_50 = ta.sma(sp500, 50)
sma_200 = ta.sma(sp500, 200)
ema_10 = ta.ema(sp500, 10)
// Market Structure Score
trend_strength = 0.0
trend_strength := trend_strength + (sp500 > sma_20 ? 1 : -1)
trend_strength := trend_strength + (sp500 > sma_50 ? 1 : -1)
trend_strength := trend_strength + (sp500 > sma_200 ? 2 : -2)
trend_strength := trend_strength + (sma_50 > sma_200 ? 2 : -2)
// Volatility Regime
returns = math.log(sp500 / sp500 )
realized_vol_20d = ta.stdev(returns, 20) * math.sqrt(252) * 100
realized_vol_60d = ta.stdev(returns, 60) * math.sqrt(252) * 100
ewma_vol = ta.ema(math.pow(returns, 2), 20)
realized_vol = math.sqrt(ewma_vol * 252) * 100
vol_premium = vix - realized_vol
// Drawdown Calculation
running_max = ta.highest(sp500, risk_lookback)
current_drawdown = (running_max - sp500) / running_max * 100
// Regime Score
regime_score = 0.0
// Trend Component (40%)
if trend_strength >= 4
regime_score := regime_score + 40
regime_score
else if trend_strength >= 2
regime_score := regime_score + 30
regime_score
else if trend_strength >= 0
regime_score := regime_score + 20
regime_score
else if trend_strength >= -2
regime_score := regime_score + 10
regime_score
else
regime_score := regime_score + 0
regime_score
// Volatility Component (30%)
if vix < 15
regime_score := regime_score + 30
regime_score
else if vix < 20
regime_score := regime_score + 25
regime_score
else if vix < 25
regime_score := regime_score + 15
regime_score
else if vix < 35
regime_score := regime_score + 5
regime_score
else
regime_score := regime_score + 0
regime_score
// Drawdown Component (30%)
if current_drawdown < 3
regime_score := regime_score + 30
regime_score
else if current_drawdown < 7
regime_score := regime_score + 20
regime_score
else if current_drawdown < 12
regime_score := regime_score + 10
regime_score
else if current_drawdown < 20
regime_score := regime_score + 5
regime_score
else
regime_score := regime_score + 0
regime_score
// Classify Regime
market_regime = regime_score >= 80 ? 'Strong Bull' : regime_score >= 60 ? 'Bull Market' : regime_score >= 40 ? 'Neutral' : regime_score >= 20 ? 'Correction' : regime_score >= 10 ? 'Bear Market' : 'Crisis'
// RISK-BASED ALLOCATION
// Calculate Market Risk
parkinson_hl = math.log(sp500_high / sp500_low)
parkinson_vol = parkinson_hl / (2 * math.sqrt(math.log(2))) * math.sqrt(252) * 100
garman_klass_vol = math.sqrt((0.5 * math.pow(math.log(sp500_high / sp500_low), 2) - (2 * math.log(2) - 1) * math.pow(math.log(sp500 / sp500 ), 2)) * 252) * 100
market_volatility_20d = math.max(ta.stdev(returns, 20) * math.sqrt(252) * 100, parkinson_vol)
market_volatility_60d = ta.stdev(returns, 60) * math.sqrt(252) * 100
market_drawdown = current_drawdown
// Initialize risk allocation
risk_allocation = 50.0
if enable_portfolio_risk_scaling
// Volatility-based allocation
vol_based_allocation = target_portfolio_volatility / math.max(market_volatility_20d, 5.0) * 100
vol_based_allocation := math.max(0, math.min(100, vol_based_allocation))
// Drawdown-based allocation
dd_based_allocation = 100.0
if market_drawdown > 1.0
dd_based_allocation := max_portfolio_drawdown / market_drawdown * 100
dd_based_allocation := math.max(0, math.min(100, dd_based_allocation))
dd_based_allocation
// Combine (conservative)
risk_allocation := math.min(vol_based_allocation, dd_based_allocation)
// Dynamic adjustment
current_equity_estimate = 50.0
estimated_portfolio_vol = current_equity_estimate / 100 * market_volatility_20d
estimated_portfolio_dd = current_equity_estimate / 100 * market_drawdown
vol_utilization = estimated_portfolio_vol / target_portfolio_volatility
dd_utilization = estimated_portfolio_dd / max_portfolio_drawdown
risk_utilization = math.max(vol_utilization, dd_utilization)
risk_adjustment_factor = 1.0
if risk_utilization > 1.0
risk_adjustment_factor := math.exp(-0.5 * (risk_utilization - 1.0))
risk_adjustment_factor := math.max(0.5, risk_adjustment_factor)
risk_adjustment_factor
else if risk_utilization < 0.9
risk_adjustment_factor := 1.0 + 0.2 * math.log(1.0 / risk_utilization)
risk_adjustment_factor := math.min(1.3, risk_adjustment_factor)
risk_adjustment_factor
risk_allocation := risk_allocation * risk_adjustment_factor
risk_allocation
else
vol_scalar = target_portfolio_volatility / math.max(market_volatility_20d, 10)
vol_scalar := math.min(1.5, math.max(0.2, vol_scalar))
drawdown_penalty = 0.0
if current_drawdown > max_portfolio_drawdown
drawdown_penalty := (current_drawdown - max_portfolio_drawdown) / max_portfolio_drawdown
drawdown_penalty := math.min(1.0, drawdown_penalty)
drawdown_penalty
risk_allocation := 100 * vol_scalar * (1 - drawdown_penalty)
risk_allocation
risk_allocation := math.max(0, math.min(100, risk_allocation))
// VALUATION ANALYSIS
// Valuation Metrics
actual_pe_ratio = spy_earnings_per_share > 0 ? sp500 / spy_earnings_per_share : spy_pe_forward
actual_earnings_yield = nz(spy_operating_earnings_yield, 0) > 0 ? spy_operating_earnings_yield : 100 / actual_pe_ratio
total_shareholder_yield = spy_dividend_yield + spy_buyback_yield
// Equity Risk Premium (multi-method calculation)
method1_erp = actual_earnings_yield - us10y
method2_erp = actual_earnings_yield + spy_buyback_yield - us10y
payout_ratio = spy_dividend_yield > 0 and actual_earnings_yield > 0 ? spy_dividend_yield / actual_earnings_yield : 0.4
sustainable_growth = spy_return_on_equity * (1 - payout_ratio) / 100
method3_erp = spy_dividend_yield + sustainable_growth * 100 - us10y
implied_growth = spy_revenue_growth * 0.7
method4_erp = total_shareholder_yield + implied_growth - us10y
equity_risk_premium = method1_erp * 0.35 + method2_erp * 0.30 + method3_erp * 0.20 + method4_erp * 0.15
ev_ebitda_ratio = spy_enterprise_value > 0 and spy_ebitda > 0 ? spy_enterprise_value / spy_ebitda : 15.0
debt_equity_health = spy_debt_to_equity < 1.0 ? 1.2 : spy_debt_to_equity < 2.0 ? 1.0 : 0.8
// Valuation Score
base_valuation_score = 50.0
if equity_risk_premium > 4
base_valuation_score := 95
base_valuation_score
else if equity_risk_premium > 3
base_valuation_score := 85
base_valuation_score
else if equity_risk_premium > 2
base_valuation_score := 70
base_valuation_score
else if equity_risk_premium > 1
base_valuation_score := 55
base_valuation_score
else if equity_risk_premium > 0
base_valuation_score := 40
base_valuation_score
else if equity_risk_premium > -1
base_valuation_score := 25
base_valuation_score
else
base_valuation_score := 10
base_valuation_score
growth_adjustment = spy_revenue_growth > 10 ? 10 : spy_revenue_growth > 5 ? 5 : 0
margin_adjustment = spy_net_margin > 15 ? 5 : spy_net_margin < 8 ? -5 : 0
roe_adjustment = spy_return_on_equity > 20 ? 5 : spy_return_on_equity < 10 ? -5 : 0
valuation_score = base_valuation_score + growth_adjustment + margin_adjustment + roe_adjustment
valuation_score := math.max(0, math.min(100, valuation_score * debt_equity_health))
// SENTIMENT ANALYSIS
// VIX Term Structure
vix_term_structure = vix9d > 0 ? vix / vix9d : 1
backwardation = vix_term_structure > 1.05
steep_backwardation = vix_term_structure > 1.15
// Safe Haven Flows
gold_momentum = ta.roc(gold, 20)
dollar_momentum = ta.roc(usd, 20)
yen_momentum = ta.roc(yen, 20)
treasury_momentum = ta.roc(tlt, 20)
safe_haven_flow = gold_momentum * 0.3 + treasury_momentum * 0.3 + dollar_momentum * 0.25 + yen_momentum * 0.15
// Advanced Sentiment Analysis
vix_percentile = ta.percentrank(vix, 252)
vix_zscore = (vix - ta.sma(vix, 252)) / ta.stdev(vix, 252)
vix_momentum = ta.roc(vix, 5)
vvix_proxy = ta.stdev(vix_momentum, 20) * math.sqrt(252)
risk_reversal_proxy = (vix - realized_vol) / realized_vol
// Sentiment Score
base_sentiment = 50.0
vix_adjustment = 0.0
if vix_zscore < -1.5
vix_adjustment := 40
vix_adjustment
else if vix_zscore < -0.5
vix_adjustment := 20
vix_adjustment
else if vix_zscore < 0.5
vix_adjustment := 0
vix_adjustment
else if vix_zscore < 1.5
vix_adjustment := -20
vix_adjustment
else
vix_adjustment := -40
vix_adjustment
term_structure_adjustment = backwardation ? -15 : steep_backwardation ? -30 : 5
vvix_adjustment = vvix_proxy > 2.0 ? -10 : vvix_proxy < 1.0 ? 10 : 0
sentiment_score = base_sentiment + vix_adjustment + term_structure_adjustment + vvix_adjustment
sentiment_score := math.max(0, math.min(100, sentiment_score))
// MACRO ANALYSIS
// Yield Curve
yield_spread_2_10 = us10y - us2y
yield_spread_3m_10 = us10y - us3m
// Credit Conditions
hyg_return = ta.roc(hyg, 20)
lqd_return = ta.roc(lqd, 20)
tlt_return = ta.roc(tlt, 20)
hyg_duration = 4.0
lqd_duration = 8.0
tlt_duration = 17.0
hyg_log_returns = math.log(hyg / hyg )
lqd_log_returns = math.log(lqd / lqd )
hyg_volatility = ta.stdev(hyg_log_returns, 20) * math.sqrt(252)
lqd_volatility = ta.stdev(lqd_log_returns, 20) * math.sqrt(252)
hyg_yield_proxy = -math.log(hyg / hyg ) * 100
lqd_yield_proxy = -math.log(lqd / lqd ) * 100
tlt_yield = us10y
hyg_spread = (hyg_yield_proxy - tlt_yield) * 100
lqd_spread = (lqd_yield_proxy - tlt_yield) * 100
hyg_distance = (hyg - ta.lowest(hyg, 252)) / (ta.highest(hyg, 252) - ta.lowest(hyg, 252))
lqd_distance = (lqd - ta.lowest(lqd, 252)) / (ta.highest(lqd, 252) - ta.lowest(lqd, 252))
default_risk_proxy = 2.0 - (hyg_distance + lqd_distance)
credit_spread = hyg_spread * 0.5 + (hyg_volatility - lqd_volatility) * 1000 * 0.3 + default_risk_proxy * 200 * 0.2
credit_spread := math.max(50, credit_spread)
credit_market_health = hyg_return > lqd_return ? 1 : -1
flight_to_quality = tlt_return > (hyg_return + lqd_return) / 2
// Macro Score
macro_score = 50.0
yield_curve_score = 0
if yield_spread_2_10 > 1.5 and yield_spread_3m_10 > 2
yield_curve_score := 40
yield_curve_score
else if yield_spread_2_10 > 0.5 and yield_spread_3m_10 > 1
yield_curve_score := 30
yield_curve_score
else if yield_spread_2_10 > 0 and yield_spread_3m_10 > 0
yield_curve_score := 20
yield_curve_score
else if yield_spread_2_10 < 0 or yield_spread_3m_10 < 0
yield_curve_score := 10
yield_curve_score
else
yield_curve_score := 5
yield_curve_score
credit_conditions_score = 0
if credit_spread < 200 and not flight_to_quality
credit_conditions_score := 30
credit_conditions_score
else if credit_spread < 400 and credit_market_health > 0
credit_conditions_score := 20
credit_conditions_score
else if credit_spread < 600
credit_conditions_score := 15
credit_conditions_score
else if credit_spread < 1000
credit_conditions_score := 10
credit_conditions_score
else
credit_conditions_score := 0
credit_conditions_score
financial_stability_score = 0
if spy_debt_to_equity < 0.5 and spy_return_on_equity > 15
financial_stability_score := 20
financial_stability_score
else if spy_debt_to_equity < 1.0 and spy_return_on_equity > 10
financial_stability_score := 15
financial_stability_score
else if spy_debt_to_equity < 1.5
financial_stability_score := 10
financial_stability_score
else
financial_stability_score := 5
financial_stability_score
macro_score := yield_curve_score + credit_conditions_score + financial_stability_score
macro_score := math.max(0, math.min(100, macro_score))
// CRISIS DETECTION
crisis_indicators = 0
if vix > crisis_vix_threshold
crisis_indicators := crisis_indicators + 1
crisis_indicators
if vix > 60
crisis_indicators := crisis_indicators + 2
crisis_indicators
if current_drawdown > crisis_drawdown_threshold
crisis_indicators := crisis_indicators + 1
crisis_indicators
if current_drawdown > 25
crisis_indicators := crisis_indicators + 1
crisis_indicators
if credit_spread > crisis_credit_spread
crisis_indicators := crisis_indicators + 1
crisis_indicators
sp500_roc_5 = ta.roc(sp500, 5)
tlt_roc_5 = ta.roc(tlt, 5)
if sp500_roc_5 < -10 and tlt_roc_5 < -5
crisis_indicators := crisis_indicators + 2
crisis_indicators
volume_spike = sp500_volume > ta.sma(sp500_volume, 20) * 2
sp500_roc_1 = ta.roc(sp500, 1)
if volume_spike and sp500_roc_1 < -3
crisis_indicators := crisis_indicators + 1
crisis_indicators
is_crisis = crisis_indicators >= 3
is_severe_crisis = crisis_indicators >= 5
// FINAL ALLOCATION CALCULATION
// Convert regime to base allocation
regime_allocation = market_regime == 'Strong Bull' ? 100 : market_regime == 'Bull Market' ? 80 : market_regime == 'Neutral' ? 60 : market_regime == 'Correction' ? 40 : market_regime == 'Bear Market' ? 20 : 0
// Normalize weights
total_weight = w_regime + w_risk + w_valuation + w_sentiment + w_macro
w_regime_norm = w_regime / total_weight
w_risk_norm = w_risk / total_weight
w_valuation_norm = w_valuation / total_weight
w_sentiment_norm = w_sentiment / total_weight
w_macro_norm = w_macro / total_weight
// Calculate Weighted Allocation
weighted_allocation = regime_allocation * w_regime_norm + risk_allocation * w_risk_norm + valuation_score * w_valuation_norm + sentiment_score * w_sentiment_norm + macro_score * w_macro_norm
// Apply Crisis Override
if use_crisis_detection
if is_severe_crisis
weighted_allocation := math.min(weighted_allocation, 10)
weighted_allocation
else if is_crisis
weighted_allocation := math.min(weighted_allocation, 25)
weighted_allocation
// Model Type Adjustment
model_adjustment = 0.0
if model_type == 'Conservative'
model_adjustment := -10
model_adjustment
else if model_type == 'Aggressive'
model_adjustment := 10
model_adjustment
else if model_type == 'Adaptive'
recent_return = (sp500 - sp500 ) / sp500 * 100
if recent_return > 5
model_adjustment := 5
model_adjustment
else if recent_return < -5
model_adjustment := -5
model_adjustment
// Apply adjustment and bounds
final_allocation = weighted_allocation + model_adjustment
final_allocation := math.max(0, math.min(100, final_allocation))
// Smooth allocation
smoothed_allocation = ta.sma(final_allocation, smoothing_period)
// Calculate portfolio risk metrics (only for internal alerts)
actual_portfolio_volatility = smoothed_allocation / 100 * market_volatility_20d
actual_portfolio_drawdown = smoothed_allocation / 100 * current_drawdown
// VISUALIZATION
// Color definitions
var color primary_color = #2196F3
var color bullish_color = #4CAF50
var color bearish_color = #FF5252
var color neutral_color = #808080
var color text_color = color.white
var color bg_color = #000000
var color table_bg_color = #1E1E1E
var color header_bg_color = #2D2D2D
switch color_scheme // Apply color scheme
'Gold' =>
primary_color := use_dark_mode ? #FFD700 : #DAA520
bullish_color := use_dark_mode ? #FFA500 : #FF8C00
bearish_color := use_dark_mode ? #FF5252 : #D32F2F
neutral_color := use_dark_mode ? #C0C0C0 : #808080
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #1A1A00 : #FFFEF0
header_bg_color := use_dark_mode ? #2D2600 : #F5F5DC
header_bg_color
'EdgeTools' =>
primary_color := use_dark_mode ? #4682B4 : #1E90FF
bullish_color := use_dark_mode ? #4CAF50 : #388E3C
bearish_color := use_dark_mode ? #FF5252 : #D32F2F
neutral_color := use_dark_mode ? #708090 : #696969
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #0F1419 : #F0F8FF
header_bg_color := use_dark_mode ? #1E2A3A : #E6F3FF
header_bg_color
'Behavioral' =>
primary_color := #808080
bullish_color := #00FF00
bearish_color := #8B0000
neutral_color := #FFBF00
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #1A1A1A : #F8F8F8
header_bg_color := use_dark_mode ? #2D2D2D : #E8E8E8
header_bg_color
'Quant' =>
primary_color := #808080
bullish_color := #FFA500
bearish_color := #8B0000
neutral_color := #4682B4
text_color := use_dark_mode ? color.white : color.black
bg_color := use_dark_mode ? #000000 : #FFFFFF
table_bg_color := use_dark_mode ? #0D0D0D : #FAFAFA
header_bg_color := use_dark_mode ? #1A1A1A : #F0F0F0
header_bg_color
'Ocean' =>
primary_color := use_dark_mode ? #20B2AA : #008B8B
bullish_color := use_dark_mode ? #00CED1 : #4682B4
bearish_color := use_dark_mode ? #FF4500 : #B22222
neutral_color := use_dark_mode ? #87CEEB : #2F4F4F
text_color := use_dark_mode ? #F0F8FF : #191970
bg_color := use_dark_mode ? #001F3F : #F0F8FF
table_bg_color := use_dark_mode ? #001A2E : #E6F7FF
header_bg_color := use_dark_mode ? #002A47 : #CCF2FF
header_bg_color
'Fire' =>
primary_color := use_dark_mode ? #FF6347 : #DC143C
bullish_color := use_dark_mode ? #FFD700 : #FF8C00
bearish_color := use_dark_mode ? #8B0000 : #800000
neutral_color := use_dark_mode ? #FFA500 : #CD853F
text_color := use_dark_mode ? #FFFAF0 : #2F1B14
bg_color := use_dark_mode ? #2F1B14 : #FFFAF0
table_bg_color := use_dark_mode ? #261611 : #FFF8F0
header_bg_color := use_dark_mode ? #3D241A : #FFE4CC
header_bg_color
'Matrix' =>
primary_color := use_dark_mode ? #00FF41 : #006400
bullish_color := use_dark_mode ? #39FF14 : #228B22
bearish_color := use_dark_mode ? #FF073A : #8B0000
neutral_color := use_dark_mode ? #00FFFF : #008B8B
text_color := use_dark_mode ? #C0FF8C : #003300
bg_color := use_dark_mode ? #0D1B0D : #F0FFF0
table_bg_color := use_dark_mode ? #0A1A0A : #E8FFF0
header_bg_color := use_dark_mode ? #112B11 : #CCFFCC
header_bg_color
'Arctic' =>
primary_color := use_dark_mode ? #87CEFA : #4169E1
bullish_color := use_dark_mode ? #00BFFF : #0000CD
bearish_color := use_dark_mode ? #FF1493 : #8B008B
neutral_color := use_dark_mode ? #B0E0E6 : #483D8B
text_color := use_dark_mode ? #F8F8FF : #191970
bg_color := use_dark_mode ? #191970 : #F8F8FF
table_bg_color := use_dark_mode ? #141B47 : #F0F8FF
header_bg_color := use_dark_mode ? #1E2A5C : #E0F0FF
header_bg_color
// Transparency settings
bg_transparency = use_dark_mode ? 85 : 92
zone_transparency = use_dark_mode ? 90 : 95
band_transparency = use_dark_mode ? 70 : 85
table_transparency = use_dark_mode ? 80 : 15
// Allocation color
alloc_color = smoothed_allocation >= 80 ? bullish_color : smoothed_allocation >= 60 ? color.new(bullish_color, 30) : smoothed_allocation >= 40 ? primary_color : smoothed_allocation >= 20 ? color.new(bearish_color, 30) : bearish_color
// Dynamic background
var color dynamic_bg_color = na
if show_regime_background
if smoothed_allocation >= 70
dynamic_bg_color := color.new(bullish_color, background_intensity)
dynamic_bg_color
else if smoothed_allocation <= 30
dynamic_bg_color := color.new(bearish_color, background_intensity)
dynamic_bg_color
else if smoothed_allocation > 60 or smoothed_allocation < 40
dynamic_bg_color := color.new(primary_color, math.min(99, background_intensity + 2))
dynamic_bg_color
bgcolor(dynamic_bg_color, title = 'Allocation Signal Background')
// Plot main allocation line
plot(smoothed_allocation, 'Equity Allocation %', color = alloc_color, linewidth = math.max(1, main_line_width))
// Reference lines (static colors for hline)
hline_bullish_color = color_scheme == 'Gold' ? use_dark_mode ? #FFA500 : #FF8C00 : color_scheme == 'EdgeTools' ? use_dark_mode ? #4CAF50 : #388E3C : color_scheme == 'Behavioral' ? #00FF00 : color_scheme == 'Quant' ? #FFA500 : color_scheme == 'Ocean' ? use_dark_mode ? #00CED1 : #4682B4 : color_scheme == 'Fire' ? use_dark_mode ? #FFD700 : #FF8C00 : color_scheme == 'Matrix' ? use_dark_mode ? #39FF14 : #228B22 : color_scheme == 'Arctic' ? use_dark_mode ? #00BFFF : #0000CD : #4CAF50
hline_bearish_color = color_scheme == 'Gold' ? use_dark_mode ? #FF5252 : #D32F2F : color_scheme == 'EdgeTools' ? use_dark_mode ? #FF5252 : #D32F2F : color_scheme == 'Behavioral' ? #8B0000 : color_scheme == 'Quant' ? #8B0000 : color_scheme == 'Ocean' ? use_dark_mode ? #FF4500 : #B22222 : color_scheme == 'Fire' ? use_dark_mode ? #8B0000 : #800000 : color_scheme == 'Matrix' ? use_dark_mode ? #FF073A : #8B0000 : color_scheme == 'Arctic' ? use_dark_mode ? #FF1493 : #8B008B : #FF5252
hline_primary_color = color_scheme == 'Gold' ? use_dark_mode ? #FFD700 : #DAA520 : color_scheme == 'EdgeTools' ? use_dark_mode ? #4682B4 : #1E90FF : color_scheme == 'Behavioral' ? #808080 : color_scheme == 'Quant' ? #808080 : color_scheme == 'Ocean' ? use_dark_mode ? #20B2AA : #008B8B : color_scheme == 'Fire' ? use_dark_mode ? #FF6347 : #DC143C : color_scheme == 'Matrix' ? use_dark_mode ? #00FF41 : #006400 : color_scheme == 'Arctic' ? use_dark_mode ? #87CEFA : #4169E1 : #2196F3
hline(show_reference_lines ? 100 : na, '100% Equity', color = color.new(hline_bullish_color, 70), linestyle = hline.style_dotted, linewidth = 1)
hline(show_reference_lines ? 80 : na, '80% Equity', color = color.new(hline_bullish_color, 40), linestyle = hline.style_dashed, linewidth = 1)
hline(show_reference_lines ? 60 : na, '60% Equity', color = color.new(hline_bullish_color, 60), linestyle = hline.style_dotted, linewidth = 1)
hline(50, '50% Balanced', color = color.new(hline_primary_color, 50), linestyle = hline.style_solid, linewidth = 2)
hline(show_reference_lines ? 40 : na, '40% Equity', color = color.new(hline_bearish_color, 60), linestyle = hline.style_dotted, linewidth = 1)
hline(show_reference_lines ? 20 : na, '20% Equity', color = color.new(hline_bearish_color, 40), linestyle = hline.style_dashed, linewidth = 1)
hline(show_reference_lines ? 0 : na, '0% Equity', color = color.new(hline_bearish_color, 70), linestyle = hline.style_dotted, linewidth = 1)
// Component plots
plot(show_components ? regime_allocation : na, 'Regime', color = color.new(#4ECDC4, 70), linewidth = 1)
plot(show_components ? risk_allocation : na, 'Risk', color = color.new(#FF6B6B, 70), linewidth = 1)
plot(show_components ? valuation_score : na, 'Valuation', color = color.new(#45B7D1, 70), linewidth = 1)
plot(show_components ? sentiment_score : na, 'Sentiment', color = color.new(#FFD93D, 70), linewidth = 1)
plot(show_components ? macro_score : na, 'Macro', color = color.new(#6BCF7F, 70), linewidth = 1)
// Confidence bands
upper_band = plot(show_confidence_bands ? math.min(100, smoothed_allocation + ta.stdev(smoothed_allocation, 20)) : na, color = color.new(neutral_color, band_transparency), display = display.none, title = 'Upper Band')
lower_band = plot(show_confidence_bands ? math.max(0, smoothed_allocation - ta.stdev(smoothed_allocation, 20)) : na, color = color.new(neutral_color, band_transparency), display = display.none, title = 'Lower Band')
fill(upper_band, lower_band, color = show_confidence_bands ? color.new(neutral_color, zone_transparency) : na, title = 'Uncertainty')
// DASHBOARD
if show_dashboard and barstate.islast
var table dashboard = table.new(position.top_right, 2, 20, border_width = 1, bgcolor = color.new(table_bg_color, table_transparency))
table.clear(dashboard, 0, 0, 1, 19)
// Header
header_color = color.new(header_bg_color, 20)
dashboard_text_color = text_color
table.cell(dashboard, 0, 0, 'DEAM', text_color = dashboard_text_color, bgcolor = header_color, text_size = size.normal)
table.cell(dashboard, 1, 0, model_type, text_color = dashboard_text_color, bgcolor = header_color, text_size = size.normal)
// Core metrics
table.cell(dashboard, 0, 1, 'Equity Allocation', text_color = dashboard_text_color, text_size = size.small)
table.cell(dashboard, 1, 1, str.tostring(smoothed_allocation, '##.#') + '%', text_color = alloc_color, text_size = size.small)
table.cell(dashboard, 0, 2, 'Cash Allocation', text_color = dashboard_text_color, text_size = size.small)
cash_color = 100 - smoothed_allocation > 70 ? bearish_color : primary_color
table.cell(dashboard, 1, 2, str.tostring(100 - smoothed_allocation, '##.#') + '%', text_color = cash_color, text_size = size.small)
// Signal
signal_text = 'NEUTRAL'
signal_color = primary_color
if smoothed_allocation >= 70
signal_text := 'BULLISH'
signal_color := bullish_color
signal_color
else if smoothed_allocation <= 30
signal_text := 'BEARISH'
signal_color := bearish_color
signal_color
table.cell(dashboard, 0, 3, 'Signal', text_color = dashboard_text_color, text_size = size.small)
table.cell(dashboard, 1, 3, signal_text, text_color = signal_color, text_size = size.small)
// Market Regime
table.cell(dashboard, 0, 4, 'Regime', text_color = dashboard_text_color, text_size = size.small)
regime_color_display = market_regime == 'Strong Bull' or market_regime == 'Bull Market' ? bullish_color : market_regime == 'Neutral' ? primary_color : market_regime == 'Crisis' ? bearish_color : bearish_color
table.cell(dashboard, 1, 4, market_regime, text_color = regime_color_display, text_size = size.small)
// VIX
table.cell(dashboard, 0, 5, 'VIX Level', text_color = dashboard_text_color, text_size = size.small)
vix_color_display = vix < 20 ? bullish_color : vix < 30 ? primary_color : bearish_color
table.cell(dashboard, 1, 5, str.tostring(vix, '##.##'), text_color = vix_color_display, text_size = size.small)
// Market Drawdown
table.cell(dashboard, 0, 6, 'Market DD', text_color = dashboard_text_color, text_size = size.small)
market_dd_color = current_drawdown < 5 ? bullish_color : current_drawdown < 10 ? primary_color : bearish_color
table.cell(dashboard, 1, 6, '-' + str.tostring(current_drawdown, '##.#') + '%', text_color = market_dd_color, text_size = size.small)
// Crisis Detection
table.cell(dashboard, 0, 7, 'Crisis Detection', text_color = dashboard_text_color, text_size = size.small)
crisis_text = is_severe_crisis ? 'SEVERE' : is_crisis ? 'CRISIS' : 'Normal'
crisis_display_color = is_severe_crisis or is_crisis ? bearish_color : bullish_color
table.cell(dashboard, 1, 7, crisis_text, text_color = crisis_display_color, text_size = size.small)
// Real Data Section
financial_bg = color.new(primary_color, 85)
table.cell(dashboard, 0, 8, 'REAL DATA', text_color = dashboard_text_color, bgcolor = financial_bg, text_size = size.small)
table.cell(dashboard, 1, 8, 'Live Metrics', text_color = dashboard_text_color, bgcolor = financial_bg, text_size = size.small)
// P/E Ratio
table.cell(dashboard, 0, 9, 'P/E Ratio', text_color = dashboard_text_color, text_size = size.small)
pe_color = actual_pe_ratio < 18 ? bullish_color : actual_pe_ratio < 25 ? primary_color : bearish_color
table.cell(dashboard, 1, 9, str.tostring(actual_pe_ratio, '##.#'), text_color = pe_color, text_size = size.small)
// ERP
table.cell(dashboard, 0, 10, 'ERP', text_color = dashboard_text_color, text_size = size.small)
erp_color = equity_risk_premium > 2 ? bullish_color : equity_risk_premium > 0 ? primary_color : bearish_color
table.cell(dashboard, 1, 10, str.tostring(equity_risk_premium, '##.##') + '%', text_color = erp_color, text_size = size.small)
// ROE
table.cell(dashboard, 0, 11, 'ROE', text_color = dashboard_text_color, text_size = size.small)
roe_color = spy_return_on_equity > 20 ? bullish_color : spy_return_on_equity > 10 ? primary_color : bearish_color
table.cell(dashboard, 1, 11, str.tostring(spy_return_on_equity, '##.#') + '%', text_color = roe_color, text_size = size.small)
// D/E Ratio
table.cell(dashboard, 0, 12, 'D/E Ratio', text_color = dashboard_text_color, text_size = size.small)
de_color = spy_debt_to_equity < 0.5 ? bullish_color : spy_debt_to_equity < 1.0 ? primary_color : bearish_color
table.cell(dashboard, 1, 12, str.tostring(spy_debt_to_equity, '##.##'), text_color = de_color, text_size = size.small)
// Shareholder Yield
table.cell(dashboard, 0, 13, 'Dividend+Buyback', text_color = dashboard_text_color, text_size = size.small)
yield_color = total_shareholder_yield > 4 ? bullish_color : total_shareholder_yield > 2 ? primary_color : bearish_color
table.cell(dashboard, 1, 13, str.tostring(total_shareholder_yield, '##.#') + '%', text_color = yield_color, text_size = size.small)
// Component Scores
component_bg = color.new(neutral_color, 80)
table.cell(dashboard, 0, 14, 'Components', text_color = dashboard_text_color, bgcolor = component_bg, text_size = size.small)
table.cell(dashboard, 1, 14, 'Scores', text_color = dashboard_text_color, bgcolor = component_bg, text_size = size.small)
table.cell(dashboard, 0, 15, 'Regime', text_color = dashboard_text_color, text_size = size.small)
regime_score_color = regime_allocation > 60 ? bullish_color : regime_allocation < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 15, str.tostring(regime_allocation, '##'), text_color = regime_score_color, text_size = size.small)
table.cell(dashboard, 0, 16, 'Risk', text_color = dashboard_text_color, text_size = size.small)
risk_score_color = risk_allocation > 60 ? bullish_color : risk_allocation < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 16, str.tostring(risk_allocation, '##'), text_color = risk_score_color, text_size = size.small)
table.cell(dashboard, 0, 17, 'Valuation', text_color = dashboard_text_color, text_size = size.small)
val_score_color = valuation_score > 60 ? bullish_color : valuation_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 17, str.tostring(valuation_score, '##'), text_color = val_score_color, text_size = size.small)
table.cell(dashboard, 0, 18, 'Sentiment', text_color = dashboard_text_color, text_size = size.small)
sent_score_color = sentiment_score > 60 ? bullish_color : sentiment_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 18, str.tostring(sentiment_score, '##'), text_color = sent_score_color, text_size = size.small)
table.cell(dashboard, 0, 19, 'Macro', text_color = dashboard_text_color, text_size = size.small)
macro_score_color = macro_score > 60 ? bullish_color : macro_score < 40 ? bearish_color : primary_color
table.cell(dashboard, 1, 19, str.tostring(macro_score, '##'), text_color = macro_score_color, text_size = size.small)
// ALERTS
// Major allocation changes
alertcondition(smoothed_allocation >= 80 and smoothed_allocation < 80, 'High Equity Allocation', 'Equity allocation reached 80% - Bull market conditions')
alertcondition(smoothed_allocation <= 20 and smoothed_allocation > 20, 'Low Equity Allocation', 'Equity allocation dropped to 20% - Defensive positioning')
// Crisis alerts
alertcondition(is_crisis and not is_crisis , 'CRISIS DETECTED', 'Crisis conditions detected - Reducing equity allocation')
alertcondition(is_severe_crisis and not is_severe_crisis , 'SEVERE CRISIS', 'Severe crisis detected - Maximum defensive positioning')
// Regime changes
regime_changed = market_regime != market_regime
alertcondition(regime_changed, 'Regime Change', 'Market regime has changed')
// Risk management alerts
risk_breach = enable_portfolio_risk_scaling and (actual_portfolio_volatility > target_portfolio_volatility * 1.2 or actual_portfolio_drawdown > max_portfolio_drawdown * 1.2)
alertcondition(risk_breach, 'Risk Breach', 'Portfolio risk exceeds target parameters')
// USAGE
// The indicator displays a recommended equity allocation percentage (0-100%).
// Example: 75% allocation = 75% stocks, 25% cash/bonds.
//
// The model combines market regime analysis (trend, volatility, drawdowns),
// risk management (portfolio-level targeting), valuation metrics (P/E, ERP),
// sentiment indicators (VIX term structure), and macro factors (yield curve,
// credit spreads) into a single allocation signal.
//
// Crisis detection automatically reduces exposure when multiple warning signals
// converge. Alerts available for major allocation shifts and regime changes.
//
// Designed for SPY/S&P 500 portfolio allocation. Adjust component weights and
// risk parameters in settings to match your risk tolerance.
View in Pine
Moving VWAP-KAMA CloudMoving VWAP-KAMA Cloud
Overview
The Moving VWAP-KAMA Cloud is a high-conviction trend filter designed to solve a major problem with standard indicators: Noise. By combining a smoothed Volume Weighted Average Price (MVWAP) with Kaufman’s Adaptive Moving Average (KAMA), this indicator creates a "Value Zone" that identifies the true structural trend while ignoring choppy price action.
Unlike brittle lines that break constantly, this cloud is "slow" by design—making it exceptionally powerful for spotting genuine trend reversals and filtering out fakeouts.
How It Works
This script uses a unique "Double Smoothing" architecture:
The Anchor (MVWAP): We take the standard VWAP and smooth it with a 30-period EMA. This represents the "Fair Value" baseline where volume has supported price over time.
The Filter (KAMA): We apply Kaufman's Adaptive Moving Average to the already smoothed MVWAP. KAMA is unique because it flattens out during low-volatility (choppy) periods and speeds up during high-momentum trends.
The Cloud:
Green/Teal Cloud: Bullish Structure (MVWAP > KAMA)
Purple Cloud: Bearish Structure (MVWAP < KAMA)
🔥 The "Reversal Slingshot" Strategy
Backtests reveal a powerful behavior during major trend changes, particularly after long bear markets:
The Resistance Phase: During a long-term downtrend, price will repeatedly rally into the Purple Cloud and get rejected. The flattened KAMA line acts as a "concrete ceiling," keeping the bearish trend intact.
The Breakout & Flip: When price finally breaks above the cloud with conviction, and the cloud flips Green, it signals a structural regime change.
The "Slingshot" Retest: Often, immediately after this flip, price will drop back into the top of the cloud. This is the "Slingshot" moment. The old resistance becomes new, hardened support.
The Rally: From this support bounce, stocks often launch into a sustained, multi-month bull run. This setup has been observed repeatedly at the bottom of major corrections.
How to Use This Indicator
1. Dynamic Support & Resistance
The KAMA Wall: When price retraces into the cloud, the KAMA line often flattens out, acting as a hard "floor" or "wall." A break of this wall usually signals a genuine trend change, not just a stop hunt.
2. Trend Confirmation (Regime Filter)
Bullish Regime: If price is holding above the cloud, only look for Long setups.
Bearish Regime: If price is holding below the cloud, only look for Short setups.
No-Trade Zone: If price is stuck inside the cloud, the market is traversing fair value. Stand aside until a clear winner emerges.
3. Multi-Timeframe Versatility
While designed for trend confirmation on higher timeframes (4H, Daily), this indicator adapts beautifully to lower timeframes (5m, 15m) for intraday scalping.
On Lower Timeframes: The cloud reacts much faster, acting as a dynamic "VWAP Band" that helps intraday traders stay on the right side of momentum during the session.
Settings
Moving VWAP Period (30): The lookback period for the base VWAP smoothing.
KAMA Settings (10, 10, 30): Controls the sensitivity of the adaptive filter.
Cloud Transparency: Adjust to keep your chart clean.
Alerts Included
Price Cross Over/Under MVWAP
Price Cross Over/Under KAMA
Cloud Flip (Bullish/Bearish Trend Change)
Tip for Traders
This is not a signal entry indicator. It is a Trend Conviction tool. Use it to filter your entries from faster indicators (like RSI or MACD). If your fast indicator signals "Buy" but the cloud is Purple, the probability is low. Wait for the Cloud Flip
Trend Mastery:The Calzolaio Way🌕 Find the God Candle. Capture the gains. Create passive income.
Fellow F.I.R.E. Decibels, disciples of the Calzolaio Way—welcome to the sacred toolkit. This indicator, "SulLaLuna 💵 Trend Mastery:The Calzolaio Way🚀," is forged from the elite SulLaLuna stack, drawing wisdom from Market Wizards like Michael Marcus (who turned $30k into $80M through disciplined trend riding) and Oliver Velez's pristine strategies for profiting on every trade. It's not just lines on a chart—it's your architectural blueprint for financial sovereignty, where data meets divine timing to build the cathedral of Project Calzolaio.
We trade math, not emotion. We honor timeframes. Confluence is King. This indicator deploys the Zero-Lag SMA (ZLSMA), Hull-based M2 (global money supply as a macro trend oracle), ATR-smart stops, and multi-TF alignments to ritualize God Candle setups. Backtested across asset classes, it's modular for your playbooks—small risks, compounding gains, passive income streams.
Why This Indicator is Awesome: The Divine Confluence Engine
In the spirit of "Use Only the Best," this tool synthesizes proven SulLaLuna indicators like ZLSMA, Adaptive Trend Finder, and Momentum HUD with Velez's lessons on trend reversals, support/resistance, and psychology of fear. Here's why it reigns supreme:
1. Global M2 Hull: Macro Trend Oracle
Scaled M2 (summed from major economies like US, EU, JP) via Hull MA captures the "big picture" (Velez Ch. 2). It flips colors as S/R—green for support (bullish bounce zones), red for resistance (bearish ceilings), orange neutral. Like Marcus spotting commodity booms, it signals when liquidity sweeps ignite God Candles. Extend it for future price projections, honoring "How a Trend Ends" (Velez Ch. 5).
2. ZLSMA + ATR Smart Stops: Surgical Precision
Zero-Lag SMA (faster than standard MAs) crosses M2 for entries, with ATR bands for initial stops (2x mult) and trails (1x mult). This embodies "Trade Small. Lose Smaller."—risk ≤1-2% per trade, pre-planned exits. Flip markers (↑/↓) alert divine timing, filtering noise like Velez's "First Pullback" setups.
3. HTF & Multi-TF Dashboard: Timeframe Alignments are Sacred
Show HTF M2 (e.g., Daily) with custom styles/colors. Multi-TF lines (4H, D, W, M) dash across your chart, labeled right-edge with 🚀 (bull) or 🛸 (bear). A confluence table (top-right) scores alignments: Strong Bull (≥3 green), Strong Bear, or Mixed. This is "Confluence is King"—no single signal rules; seek 4+ star scores like Rogers buying value in hysteria.
4. Background & Ribbon: Visual Divine Guidance
Slope-based bgcolor (green bull, red bear) for at-a-glance bias. M2 Ribbon (EMA cloud) flips triangles for macro shifts, ritualizing climactic reversals (Velez Ch. 7).
5. Composite Probability: High-Prob God Candle Hunter
Scores (0-100%) blend 8 factors: price/ZLSMA vs M2, TF slopes, ribbon. Threshold (70%) + pivot zone (near M2/ATR) + optional cross filters for HP signals. Labels show "%" dynamically—alerts fire when confluence ≥4, echoing Schwartz's champion edge: "Everybody Gets What They Want" (Seykota wisdom).
6. Alerts & Rituals Built-In
M2 flips, entries/exits, HP longs/shorts—log them in your journal. Weekly reviews dissect anomalies, as per our Operational Framework.
This isn't hype—it's audited excellence. Backtest it: High confluence crushes drawdowns, compounding like Bielfeldt's T-bond mastery from Peoria. We build together; share wins in the F.I.R.E. Decibel forum.
Suggested Strategy: The SulLaLuna M2 Confluence Playbook
Honor the Risk Triad: Position ↓ if leverage/timeframe ↑; scale ↑ only on ≥4 confluence. Align with "God Candle" hunts—rare explosives reverse-engineered for passive streams.
1. Pre-Trade Checklist (Before Every Entry)
- Trend Alignment: D/4H/1H M2 slopes agree? Table shows Strong Bull/Bear?
- Signal on 15m: ZLSMA crosses M2 in confluence zone (near pivot/ATR bands).
- Volume + Divergence**: Supported by volume (use HUD if added); score ≥70%.
- SL/TP Setup: ATR-based stop; TP at structure/2-3R reward (Velez Reward:Risk).
- HTF Agrees: Monthly bull for longs; avoid counter-trend unless climactic (Ch. 7).
Confluence Score: Rate 1-5 stars. <3? Stand aside. Log emotional state—no adrenaline.
2. Execution Protocol
- Entry: On HP Long/Short triangle (e.g., ZLSMA > M2, score 80%+, monthly bull). Use limits; favor longs above M2 support.
- Position Size: ≤1-2% risk. Example: $10k account, 1% risk = $100 SL distance → size accordingly.
- Trail Stops: Move to trail band after 1R profit; let winners run like Kovner's world trades.
- Asset Classes**: Forex/stocks/crypto—test M2's macro edge on EURUSD or NASDAQ (Velez Ch. 6 reviews).
Ritualize: "When we find the God Candele, we don’t just ride it—we ritualize it." Screenshot + reason.
3. Post-Trade Ritual
- Document: Result, confluence score, lessons. Update journal.
- Exits: Hit stop/exit cross? Or trail locks gains.
- Weekly Audit: Wins/losses, anomalies. Adjust params (e.g., M2 length 55 default).
4. Risk Triad in Action
- Low TF (15m)? Smaller size.
- High Leverage? Tiny positions.
- Confluence ≥4 + HTF support? Scale hold for passive compounding.
Example Setup: God Candle Long
- Chart: 15m EURUSD.
- M2 Hull green (support), ZLSMA crossover, 4H/D/W bull (table: Strong Bull).
- HP Long (85% score) near pivot.
- Entry: Limit at cross; SL below ATR lower; TP at next resistance.
- Outcome: Capture 2R gain; trail for more if trend day (Velez Ch. 5).
Community > Ego: Test, share signals in Discord. Backtest in Pine Script for algo evolution.
We are architects of redemption. Each trade bricks the cathedral. Trade the micro, flow with the macro. When alignments converge, we act—with discipline, data, and divine purpose.
Volume Divergence(FULLAUTO)MINHPHUOCKBVolume Divergence( 5 COLOR)
BB50
AUTO TIME
bullishDivergence = color.lime
bearishDivergence =color.red
volSpike =color.rgb
volContraction = color.aqua
incVolTrend =color.new
decVolTrend =color.new
color.rgb
Filter Wave1. Indicator Name
Filter Wave
2. One-line Introduction
A visually enhanced trend strength indicator that uses linear regression scoring to render smoothed, color-shifting waves synced to price action.
3. General Overview
Filter Wave+ is a trend analysis tool designed to provide an intuitive and visually dynamic representation of market momentum.
It uses a pairwise comparison algorithm on linear regression values over a lookback period to determine whether price action is consistently moving upward or downward.
The result is a trend score, which is normalized and translated into a color-coded wave that floats above or below the current price. The wave's opacity increases with trend strength, giving a visual cue for confidence in the trend.
The wave itself is not a raw line—it goes through a three-stage smoothing process, producing a natural, flowing curve that is aesthetically aligned with price movement.
This makes it ideal for traders who need a quick visual context before acting on signals from other tools.
While Filter Wave+ does not generate buy/sell signals directly, its secure and efficient design allows it to serve as a high-confidence trend filter in any trading system.
4. Key Advantages
🌊 Smooth, Dynamic Wave Output
3-stage smoothed curves give clean, flowing visual feedback on market conditions.
🎨 Trend Strength Visualized by Color Intensity
Stronger trends appear with more solid coloring, while weak/neutral trends fade visually.
🔍 Quantitative Trend Detection
Linear regression ordering delivers precise, math-based trend scoring for confidence assessment.
📊 Price-Synced Floating Wave
Wave is dynamically positioned based on ATR and price to align naturally with market structure.
🧩 Compatible with Any Strategy
No conflicting signals—Filter Wave+ serves as a directional overlay that enhances clarity.
🔒 Secure Core Logic
Core algorithm is lightweight and secure, with minimal code exposure and strong encapsulation.
📘 Indicator User Guide
📌 Basic Concept
Filter Wave+ calculates trend direction and intensity using linear regression alignment over time.
The resulting wave is rendered as a smoothed curve, colored based on trend direction (green for up, red for down, gray for neutral), and adjusted in transparency to reflect trend strength.
This allows for fast trend interpretation without overwhelming the chart with signals.
⚙️ Settings Explained
Lookback Period: Number of bars used for pairwise regression comparisons (higher = smoother detection)
Range Tolerance (%): Threshold to qualify as an up/down trend (lower = more sensitive)
Regression Source: The price input used in regression calculation (default: close)
Linear Regression Length: The period used for the core regression line
Bull/Bear Color: Customize the color for bullish and bearish waves
📈 Timing Example
Wave color changes to green and becomes more visible (less transparent)
Wave floats above price and aligns with an uptrend
Use as trend confirmation when other signals are present
📉 Timing Example
Wave shifts to red and darkens, floating below the price
Regression direction down; price continues beneath the wave
Acts as bearish confirmation for short trades or risk-off positioning
🧪 Recommended Use Cases
Use as a trend confidence overlay on your existing strategies
Especially useful in swing trading for detecting and confirming dominant market direction
Combine with RSI, MACD, or price action for high-accuracy setups
🔒 Precautions
This is not a signal generator—intended as a trend filter or directional guide
May respond slightly slower in volatile reversals; pair with responsive indicators
Wave position is influenced by ATR and price but does not represent exact entry/exit levels
Parameter optimization is recommended based on asset class and timeframe
Order Flow AnalysisOrder Flow Pressure Suite — Wick, Volume & Absorption-Based Pressure Map
This indicator builds a composite buying/selling pressure score from candle structure, volume behavior, and absorption signals.
It is designed to infer the “intent” behind price moves by looking at how candles form, where they close, and how volume behaves — even without access to true bid/ask or footprint data.
Core Concepts
Wick-to-Body Analysis
The script evaluates the ratio of upper and lower wicks to the total candle range.
Strong wicks with relatively small bodies are treated as rejections :
Long upper wick → potential selling pressure / rejection of higher prices
Long lower wick → potential buying pressure / rejection of lower prices
Close Position Analysis
The close is normalized within the candle range:
Close near the high → bullish pressure
Close near the low → bearish pressure
Close near the middle → more neutral , context taken from wicks and volume
Volume Delta Estimation
Since true bid/ask data is not available on standard charts, the script estimates “volume delta” by distributing total volume between buyers and sellers based on candle characteristics:
Bull candles receive more “buying volume,” weighted toward closes near the high
Bear candles receive more “selling volume,” weighted toward closes near the low
This is an approximation of order flow, not a direct time & sales feed.
Absorption Detection
The script looks for candles where volume is high but price movement is relatively small .
This combination often suggests:
Bullish absorption → buyers absorbing aggressive selling (potential accumulation)
Bearish absorption → sellers absorbing aggressive buying (potential distribution)
Absorption zones are tracked over a configurable lookback and can be shaded in the background.
Composite Pressure Oscillator
All the above components (wicks, close position, heuristic volume delta, absorption bias) are blended into a single pressure score :
Values > 0 → net buying pressure
Values < 0 → net selling pressure
The raw score is smoothed with an EMA to reduce noise and create a cleaner oscillator line.
Divergence Detection
The indicator compares price pivots to pressure pivots:
Bullish divergence : price makes a lower low while pressure makes a higher low
Bearish divergence : price makes a higher high while pressure makes a lower high
These conditions can help highlight potential exhaustion or hidden participation from larger players.
Visual Elements
Histogram showing the intensity of buying/selling pressure
Color-coding for increasing vs. decreasing pressure
Background shading for detected absorption zones
Status table summarizing current pressure, trend bias, volume delta, wick signal, and absorption state in real time
How To Use
Use the pressure oscillator to gauge whether the current bar sequence is dominated by buyers or sellers. Strong positive readings may indicate sustained buying pressure; strong negatives may indicate sustained selling pressure.
Watch for divergences between price and the pressure oscillator around key levels, swings, or zones you already care about.
Use absorption zones and wick rejection signals as additional context around support/resistance, breakouts, or failed moves.
Treat all signals as context and confluence , not as stand-alone trade entries or exits. This tool is best used alongside your existing price action, volume, and risk management framework.
Important Notes & Limitations
This script does not access real bid/ask, footprint, or order book data . All volume delta and absorption interpretations are heuristic estimates derived from OHLCV candles.
Signals are probabilistic , not guarantees. They can be early, late, or outright wrong in fast or low-liquidity markets.
Always validate signals with your own analysis, timeframe alignment, and risk management. This indicator is intended as an analytical tool , not financial advice.
MAHI Indicator v9.5 - Smart Momentum HUD + IntradayMAHI Indicator v9.5 — Smart Momentum HUD (Multi-Framework + Intraday Engine)
A Complete Momentum, Trend, and Setup Framework for Swing, Position & Intraday Traders
MAHI v9.5 is the most advanced version yet — a highly optimized, visual, multi-framework trading system that blends momentum, trend alignment, adaptive setup detection, and now Auto-Intraday Mode for short-term traders.
This indicator acts like a Heads-Up Display (HUD) on your chart: it shows trend strength, squeeze zones, dynamic support/resistance, EMAs, setup validation, and early reversal signals in one clean interface — without clutter.
✔ Core Features
📌 1. Smart Momentum Ribbon
A dynamic EMA-based momentum band that visually shifts as trend strength changes.
Helps identify strong vs. weak momentum zones
Adapts to volatility & trend slope
Works on all timeframes (1m to 1M)
📌 2. EMA 9 → 21 Flip System
A precision trend-switching signal:
EMA 9 → 21 BULL = early bullish momentum
EMA 9 → 21 BEAR = early bearish momentum
More reliable than stand-alone MA crossovers
📌 3. Bullish Setup Engine (Standard + Weak)
Automatically identifies when price is entering a reversal-ready state based on:
Position relative to the ribbon
Candle structure
Momentum compression
Slope + exhaustion conditions
Includes:
Bull Setup (Standard) — Higher probability setup
Bull Setup (Weak) — Early or less developed setup
Setup Invalidated — Confirms that the pattern failed
This prevents false confidence & keeps traders disciplined.
📌 4. Strong Buy / Strong Sell Signals
Only appear when multiple confirmations align:
Ribbon bias
EMA slope
Momentum compression
Trend alignment
Filtered to remove noise — especially in lower timeframes.
📌 5. Multi-Timeframe Trend HUD
Top-right panel summarizing:
Overall Trend (Bullish, Bearish, Neutral)
RSI Condition
Daily vs Weekly Alignment
Trading Mode Suggestions (Buy / Sell / LEAPS / Neutral)
This gives instant context.
📌 6. Auto Intraday Engine (NEW in v9.5)
Automatically switches internal logic when you move into intraday timeframes (1m–30m):
Intraday Enhancements:
Adaptive setup detection
Faster momentum sensitivity
EMAs tuned for scalp/swing precision
Tighter invalidation logic
Reduced false positives
Optional strict filtering
Perfect for scalping, day trading & micro-trends
Works instantly — no settings needed.
Just change the chart timeframe and MAHI adjusts.
📌 7. Dynamic High-Timeframe Support (W & M)
Auto-layers weekly & monthly levels:
Helps identify strong bounce zones
Extremely useful for swing & LEAPS traders
📌 8. Weekly Volume Shelf Projection
Lightweight VWAP-style level based on weekly volume aggregation.
Shows probable bottoming areas during pullbacks.
✔ Who This Indicator Is For
Perfect for:
Day traders
Swing traders
Momentum riders
LEAPS & long-term investors
Beginner traders needing a structured system
MAHI adapts to your timeframe and trading style.
✔ Why MAHI Works
MAHI isn’t a single-signal indicator — it’s a framework.
It combines:
Trend
Momentum
Volatility
Setup pattern detection
Validation & invalidation
Multi-timeframe alignment
Dynamic zones
Intraday optimization
This eliminates guesswork and helps traders avoid the emotional traps that cause most losses.
You don’t just get a signal — you get context.
✔ How to Use It
Follow the ribbon bias
Use EMA 9→21 flips as trend confirmation
Look for Bull Setup tags during pullbacks
Avoid trades when you see Setup Invalidated
Respect weekly/monthly HTF support levels
On intraday charts — rely on auto-optimized mode
For swing entries, combine setups with HTF trend HUD
MAHI gives the map. You choose the path.
✔ Final Notes
This version is heavily optimized for performance, clarity, and high-probability signals.
MAHI does not repaint, and works on all assets including:
Stocks
Crypto
ETFs
Forex
Futures
Simple Line📌 Understanding the Basic Concept
The trend reverses only when the price moves up or down by a fixed filter size.
It ignores normal volatility and noise, recognizing a trend change only when price moves beyond a specified threshold.
Trend direction is visually intuitive through line colors (green: uptrend, red: downtrend).
⚙️ Explanation of Settings
Auto Brick Size: Automatically determines the brick/filter size.
Fixed Brick Size: Manually set the size (e.g., 15, 30, 50, 100, etc.).
Volatility Length: The lookback period used for calculations (default: 14).
📈 Example of Identifying Buy Timing
When the line changes from gray or red to green, it signals the start of an uptrend.
This indicates that the price has moved upward by more than the required threshold.
📉 Example of Identifying Sell Timing
When the line changes from green to red, it suggests a possible downtrend reversal.
At this point, consider closing long positions or evaluating short entries.
🧪 Recommended Use Cases
Use as a trend filter to enhance the accuracy of existing strategies.
Can be used alone as a clean directional indicator without complex oscillators.
Works synergistically with trend-following strategies, breakout strategies, and more.
🔒 Notes & Cautions
More suitable for medium- to long-term trend trading than for fast scalping.
If the brick size is too small, the indicator may react to noise.
Sensitivity varies greatly depending on the selected brick size, so backtesting is essential to determine optimal values.
❗ The Trend Simple Line focuses solely on direction—remove the noise and focus purely on the trend.
초대 전용 스크립트
이 스크립트에 대한 접근이 제한되어 있습니다. 사용자는 즐겨찾기에 추가할 수 있지만 사용하려면 사용자의 권한이 필요합니다. 연락처 정보를 포함하여 액세스 요청에 대한 명확한 지침을 제공해 주세요.
이 비공개 초대 전용 스크립트는 스크립트 모더레이터의 검토를 거치지 않았으며, 하우스 룰 준수 여부는 확인되지 않았습니다. 트레이딩뷰는 스크립트의 작동 방식을 충분히 이해하고 작성자를 완전히 신뢰하지 않는 이상, 해당 스크립트에 비용을 지불하거나 사용하는 것을 권장하지 않습니다. 커뮤니티 스크립트에서 무료 오픈소스 대안을 찾아보실 수도 있습니다.
작성자 지시 사항
.
c9indicator
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니






















