FVG Scanner ProFVG Scanner Pro — Smart Fair Value Gap Detector (with HTF context & proximity alerts)
What it does
FVG Scanner Pro automatically finds Fair Value Gaps (FVGs) on your current chart and (optionally) on a higher timeframe (HTF), draws them as color-coded zones, and notifies you when price comes close to a gap boundary using an ADR-based proximity trigger and (optional) volume confirmation. It’s designed for ICT-style gap trading, confluence building, and clean visual execution.
How it works:
FVG definition
* Bullish FVG (gap up): low > high  (the current candle’s low is above the high 2 bars ago).
* Bearish FVG (gap down): high < low  (the current candle’s high is below the low 2 bars ago).
* Gaps smaller than your Min FVG Size (%) are ignored. (Gap size = (top-bottom)/bottom * 100.)
Higher-timeframe logic (auto-selected)
The script auto picks a sensible HTF:
1–5m → 15m, 15m → 1H, 1H → 4H, 4H → 1D, 1D → 1W, 1W → 1M, small 1M → 3M, big ≥3M → 12M.
You can display HTF FVGs and even filter so current-TF FVGs only show when they overlap an HTF gap.
Proximity alerts (ADR-based)
The script computes ADR on the current chart timeframe over a user-set lookback (default 20 bars).
An alert fires when price moves toward the closest actionable boundary and comes within ADR × Multiplier:
Bullish: price moving down, within distance of the bottom of a bullish FVG.
Bearish: price moving up, within distance of the top of a bearish FVG.
Yellow ▲/▼ markers show where a proximity alert triggered.
Volume filter (optional)
Require volume to be greater than SMA(20) × multiplier to accept a newly formed FVG.
Lifecycle
Each gap remains active for Extend FVG Box (Bars) bars.
You can delete the box after fill, or keep filled gaps visible as gray zones, or hide them.
Color legend
Current-TF Bullish: Pink/Magenta box
Current-TF Bearish: Cyan/Turquoise box
HTF Bullish: Gold box
HTF Bearish: Orange box
Filled (if shown): Gray box
Alert markers: Yellow ▲ (bullish), Yellow ▼ (bearish)
Inputs (what to tweak)
Show FVGs: Bullish / Bearish / Both
Max Bars Back to Find FVG: collection window & cleanup guard
Extend FVG Box (Bars): how long a zone stays tradable/active
Min FVG Size (%): ignore micro gaps
Delete Box After Fill & Show Filled FVGs: choose how you want completed gaps handled
Show Alert Markers: show/hide the yellow proximity arrows
Show Higher Timeframe FVG: overlay HTF gaps (auto TF)
HTF Filter: only display current-TF gaps that overlap an HTF gap
ADR Lookback & Proximity Multiplier: tune alert sensitivity to your market & timeframe
Volume Filter & Volume > MA Multiple: require above-average volume for new gaps
Built-in alerts (ready to use)
Create alerts in TradingView (⚠️ “Once per bar” or “Once per bar close”, your choice) and select from:
🟢 Bullish FVG Proximity — price approaching a bullish gap bottom
🔴 Bearish FVG Proximity — price approaching a bearish gap top
✅ New Bullish FVG Formed
⚠️ New Bearish FVG Formed
The alert messages include the symbol and price; proximity markers are also plotted on chart.
Tips & best practices
Use FVGs with market structure (break of structure, swing points), order blocks, or liquidity pools for confluence.
On very low timeframes, raise Min FVG Size and/or lower Max Bars Back to reduce noise and keep things fast.
Extend FVG Box controls how long a zone is considered valid; align it with your holding horizon (scalp vs swing).
Information panel (top-right)
Shows your mode, current HTF, number of gaps in memory, active bull/bear counts, and current-TF ADR.
在腳本中搜尋"bear"
RSI Divergence + Hidden RSI Divergence + Hidden (TV-like pairing, final)
What it does
This indicator plots RSI and automatically detects both regular and hidden divergences by pairing RSI pivots with price pivots. It supports a TradingView-like loose pairing (within a user-defined bar tolerance) and a strict same-bar pairing. Detected signals are drawn with lines and optional labels on the RSI pane for quick visual verification.
Divergence logic
Regular Bullish (label: Bull)
Price makes a lower low while RSI makes a higher low → potential upward reversal.
Regular Bearish (label: Bear)
Price makes a higher high while RSI makes a lower high → potential downward reversal.
Hidden Bullish (label: H_Bull)
Price makes a higher low while RSI makes a lower low → trend-continuation bias upward.
Hidden Bearish (label: H_Bear)
Price makes a lower high while RSI makes a higher high → trend-continuation bias downward.
All conditions use pivot-to-pivot comparisons with optional equality tolerance for price and RSI to reduce false “equal” mismatches.
Pairing modes
TV-like
Pairs the latest price and RSI pivots if their pivot bars occur within ±tolBars.
A lightweight “pending” buffer allows pairing a newly detected pivot with a recent opposite pivot that arrived a few bars earlier/later (within tolerance).
Same Bar
Price and RSI pivots must occur on the exact same bar to form a pair.
Key inputs
RSI Source & Length: srcRsi, rsiLen (default 14). RSI line and reference levels (70/50/30) can be shown/hidden.
Pivot Window: leftBars, rightBars for both price and RSI pivots.
Pairing: pairMode = TV-like or Same Bar; tolBars for bar tolerance (TV-like only).
Price Pivot Basis: priceMode = High/Low (default) or Close.
Equality Tolerance:
allowEqual (use >=/<=),
priceEpsTks (ticks) for price equality slack,
rsiEps (points) for RSI equality slack.
Visibility: showRSI, showRegular, showHidden, showLabels.
Visuals
Lines (on RSI):
Regular Bearish: red
Regular Bullish: lime
Hidden Bearish: orange
Hidden Bullish: teal
Labels (optional): "Bear", "Bull", "H_Bear", "H_Bull" placed on the RSI series at the second pivot.
Alerts
Four alert conditions are provided and fire when the corresponding divergence is confirmed:
Bear (Regular)
Bull (Regular)
H_Bear (Hidden)
H_Bull (Hidden)
Notes & tips
Divergences are evaluated only when both price and RSI pivots exist and can be paired under the selected mode.
Pivot sensitivity: smaller leftBars/rightBars → earlier but noisier signals; larger values → fewer, more stable pivots.
Tolerance: If you miss valid setups because pivots land a few bars apart, use TV-like with a small tolBars (e.g., 1–2). If you prefer stricter confirmation, use Same Bar.
Equality slack: Use priceEpsTks and rsiEps to avoid rejecting near-equal highs/lows due to tiny differences.
Works on any symbol/timeframe; as with all divergence tools, treat signals as context—combine with trend, structure, and risk management.
Dashboard Trends📊 Dashboard Trends + Anchored Daily VWAP
This indicator provides a real-time multi-timeframe trend dashboard alongside a daily anchored VWAP system, helping you assess both macro and intraday market sentiment at a glance.
🔍 Key Features
✅ Multi-Timeframe Trend Analysis
Tracks whether EMA(22) is above EMA(200) across:
1m, 10m, 30m, 4h, 1D timeframes
Color-coded "Bullish"/"Bearish" status for each
Aggregated trend summary using 6 signals (including VWAP)
✅ Anchored Daily VWAP
Uses ta.vwap to provide a session-resetting daily VWAP
VWAP resets at the beginning of each trading day
Live update throughout the day
Supports pre-market and after-hours if chart includes ETH
✅ VWAP Bands (±1σ to ±3σ)
Optional bands show price deviation from VWAP
Fully customizable:
Enable/disable each band
Set deviation multiplier
Adjust color and visibility
✅ Visual Dashboard
Table display in the bottom-right corner
Shows trend status per timeframe + VWAP + Summary
Easy-to-read green/yellow/red color codes
⚙️ Customization
Toggle VWAP line on/off
Enable or disable any band level
Adjust standard deviation multiplier
Choose your VWAP and band colors
🧠 Summary Logic
Strong Bull: 6 bullish signals
Bull: 5 signals
Mixed: 3–4 signals
Bear: 2 signals
Strong Bear: 0–1 signals
This tool is perfect for traders looking to combine trend-following and intraday mean-reversion awareness, with all the critical data visualized in one compact dashboard.
Trend Gauge [BullByte]Trend Gauge  
 Summary 
A multi-factor trend detection indicator that aggregates EMA alignment, VWMA momentum scaling, volume spikes, ATR breakout strength, higher-timeframe confirmation, ADX-based regime filtering, and RSI pivot-divergence penalty into one normalized trend score. It also provides a confidence meter, a Δ Score momentum histogram, divergence highlights, and a compact, scalable dashboard for at-a-glance status.
________________________________________
 ## 1. Purpose of the Indicator 
 Why this was built 
Traders often monitor several indicators in parallel - EMAs, volume signals, volatility breakouts, higher-timeframe trends, ADX readings, divergence alerts, etc., which can be cumbersome and sometimes contradictory. The  “Trend Gauge”  indicator was created to consolidate these complementary checks into a single, normalized score that reflects the prevailing market bias (bullish, bearish, or neutral) and its strength. By combining multiple inputs with an adaptive regime filter, scaling contributions by magnitude, and penalizing weakening signals (divergence), this tool aims to reduce noise, highlight genuine trend opportunities, and warn when momentum fades.
 Key Design Goals 
 Signal Aggregation 
Merged  trend-following signals  (EMA crossover, ATR breakout, higher-timeframe confirmation) and  momentum signals (VWMA thrust, volume spikes) into a unified score that reflects directional bias more holistically.
 Market Regime Awareness 
Implemented an ADX-style filter to distinguish between trending and ranging markets, reducing the influence of trend signals during sideways phases to avoid false breakouts.
 Magnitude-Based Scaling 
Replaced binary contributions with scaled inputs: VWMA thrust and ATR breakout are weighted relative to recent averages, allowing for more nuanced score adjustments based on signal strength.
 Momentum Divergence Penalty 
Integrated pivot-based RSI divergence detection to slightly reduce the overall score when early signs of momentum weakening are detected, improving risk-awareness in entries.
 Confidence Transparency 
Added a live confidence metric that shows what percentage of enabled sub-indicators currently agree with the overall bias, making the scoring system more interpretable.
 Momentum Acceleration Visualization 
Plotted the change in score (Δ Score) as a histogram bar-to-bar, highlighting whether momentum is increasing, flattening, or reversing, aiding in more timely decision-making.
 Compact Informational Dashboard 
Presented a clean, scalable dashboard that displays each component’s status, the final score, confidence %, detected regime (Trending/Ranging), and a labeled strength gauge for quick visual assessment.
________________________________________
 ## 2. Why a Trader Should Use It 
 Main benefits and use cases 
1.	 Unified View:  Rather than juggling multiple windows or panels, this indicator delivers a single score synthesizing diverse signals.
2.	 Regime Filtering:  In ranging markets, trend signals often generate false entries. The ADX-based regime filter automatically down-weights trend-following components, helping you avoid chasing false breakouts.
3.	 Nuanced Momentum & Volatility:  VWMA and ATR breakout contributions are normalized by recent averages, so strong moves register strongly while smaller fluctuations are de-emphasized.
4.	 Early Warning of Weakening:  Pivot-based RSI divergence is detected and used to slightly reduce the score when price/momentum diverges, giving a cautionary signal before a full reversal.
5.	 Confidence Meter:  See at a glance how many sub-indicators align with the aggregated bias (e.g.,  “80% confidence” means 4 out of 5 components agree ). This transparency avoids black-box decisions.
6.	 Trend Acceleration/Deceleration View:  The Δ Score histogram visualizes whether the aggregated score is rising (accelerating trend) or falling (momentum fading), supplementing the main oscillator.
7.	 Compact Dashboard:  A corner table lists each check’s status (“Bull”, “Bear”, “Flat” or “Disabled”), plus overall Score, Confidence %, Regime, Trend Strength label, and a gauge bar. Users can scale text size (Normal, Small, Tiny) without removing elements, so the full picture remains visible even in compact layouts.
8.	 Customizable & Transparent:  All components can be enabled/disabled and parameterized (lengths, thresholds, weights). The full Pine code is open and well-commented, letting users inspect or adapt the logic.
9.	 Alert-ready:  Built-in alert conditions fire when the score crosses weak thresholds to bullish/bearish or returns to neutral, enabling timely notifications.
________________________________________
 ## 3. Component Rationale (“Why These Specific Indicators?”) 
Each sub-component was chosen because it adds complementary information about trend or momentum:
1.	 EMA Cross 
o	Basic trend measure: compares a faster EMA vs. a slower EMA. Quickly reflects trend shifts but by itself can whipsaw in sideways markets.
2.	 VWMA Momentum 
o	Volume-weighted moving average change indicates momentum with volume context. By normalizing (dividing by a recent average absolute change), we capture the strength of momentum relative to recent history. This scaling prevents tiny moves from dominating and highlights genuinely strong momentum.
3.	 Volume Spikes 
o	Sudden jumps in volume combined with price movement often accompany stronger moves or reversals. A binary detection (+1 for bullish spike, -1 for bearish spike) flags high-conviction bars.
4.	 ATR Breakout 
o	Detects price breaking beyond recent highs/lows by a multiple of ATR. Measures breakout strength by how far beyond the threshold price moves relative to ATR, capped to avoid extreme outliers. This gives a volatility-contextual trend signal.
5.	 Higher-Timeframe EMA Alignment 
o	Confirms whether the shorter-term trend aligns with a higher timeframe trend. Uses request.security with lookahead_off to avoid future data. When multiple timeframes agree, confidence in direction increases.
6.	 ADX Regime Filter (Manual Calculation) 
o	Computes directional movement (+DM/–DM), smoothes via RMA, computes DI+ and DI–, then a DX and ADX-like value. If ADX ≥ threshold, market is “Trending” and trend components carry full weight; if ADX < threshold, “Ranging” mode applies a configurable weight multiplier (e.g., 0.5) to trend-based contributions, reducing false signals in sideways conditions. Volume spikes remain binary (optional behavior; can be adjusted if desired).
7.	 RSI Pivot-Divergence Penalty 
o	Uses ta.pivothigh / ta.pivotlow with a lookback to detect pivot highs/lows on price and corresponding RSI values. When price makes a higher high but RSI makes a lower high (bearish divergence), or price makes a lower low but RSI makes a higher low (bullish divergence), a divergence signal is set. Rather than flipping the trend outright, the indicator subtracts (or adds) a small penalty (configurable) from the aggregated score if it would weaken the current bias. This subtle adjustment warns of weakening momentum without overreacting to noise.
8.	 Confidence Meter 
o	Counts how many enabled components currently agree in direction with the aggregated score (i.e., component sign × score sign > 0). Displays this as a percentage. A high percentage indicates strong corroboration; a low percentage warns of mixed signals.
9.	 Δ Score Momentum View 
o	Plots the bar-to-bar change in the aggregated score (delta_score = score - score ) as a histogram. When positive, bars are drawn in green above zero; when negative, bars are drawn in red below zero. This reveals acceleration (rising Δ) or deceleration (falling Δ), supplementing the main oscillator.
10.	 Dashboard 
•	A table in the indicator pane’s top-right with 11 rows:
1.	EMA Cross status
2.	VWMA Momentum status
3.	Volume Spike status
4.	ATR Breakout status
5.	Higher-Timeframe Trend status
6.	Score (numeric)
7.	Confidence %
8.	Regime (“Trending” or “Ranging”)
9.	Trend Strength label (e.g., “Weak Bullish Trend”, “Strong Bearish Trend”)
10.	Gauge bar visually representing score magnitude
•	All rows always present; size_opt (Normal, Small, Tiny) only changes text size via text_size, not which elements appear. This ensures full transparency.
________________________________________
 ## 4. What Makes This Indicator Stand Out 
•	 Regime-Weighted Multi-Factor Score:  Trend and momentum signals are adaptively weighted by market regime  (trending vs. ranging) , reducing false signals.
•	 Magnitude Scaling:  VWMA and ATR breakout contributions are normalized by recent average momentum or ATR, giving finer gradation compared to simple ±1.
•	 Integrated Divergence Penalty:  Divergence directly adjusts the aggregated score rather than appearing as a separate subplot; this influences alerts and trend labeling in real time.
•	 Confidence Meter:  Shows the percentage of sub-signals in agreement, providing transparency and preventing blind trust in a single metric.
•	 Δ Score Histogram Momentum View:  A histogram highlights acceleration or deceleration of the aggregated trend score, helping detect shifts early.
•	 Flexible Dashboard:  Always-visible component statuses and summary metrics in one place; text size scaling keeps the full picture available in cramped layouts.
•	 Lookahead-Safe HTF Confirmation:  Uses lookahead_off so no future data is accessed from higher timeframes, avoiding repaint bias.
•	 Repaint Transparency:  Divergence detection uses pivot functions that inherently confirm only after lookback bars; description documents this lag so users understand how and when divergence labels appear.
•	 Open-Source & Educational:  Full, well-commented Pine v6 code is provided; users can learn from its structure: manual ADX computation, conditional plotting with series = show ? value : na, efficient use of table.new in barstate.islast, and grouped inputs with tooltips.
•	 Compliance-Conscious:  All plots have descriptive titles; inputs use clear names; no unnamed generic “Plot” entries; manual ADX uses RMA; all request.security calls use lookahead_off. Code comments mention repaint behavior and limitations.
________________________________________
 ## 5. Recommended Timeframes & Tuning 
•	 Any Timeframe:  The indicator works on small (e.g., 1m) to large (daily, weekly) timeframes. However:
o	On very low timeframes (<1m or tick charts), noise may produce frequent whipsaws. Consider increasing smoothing lengths, disabling certain components (e.g., volume spike if volume data noisy), or using a larger pivot lookback for divergence.
o	On higher timeframes (daily, weekly), consider longer lookbacks for ATR breakout or divergence, and set Higher-Timeframe trend appropriately (e.g., 4H HTF when on 5 Min chart).
•	 Defaults & Experimentation:  Default input values are chosen to be balanced for many liquid markets. Users should test with replay or historical analysis on their symbol/timeframe and adjust:
o	ADX threshold (e.g., 20–30) based on instrument volatility.
o	VWMA and ATR scaling lengths to match average volatility cycles.
o	Pivot lookback for divergence: shorter for faster markets, longer for slower ones.
•	 Combining with Other Analysis:  Use in conjunction with price action, support/resistance, candlestick patterns, order flow, or other tools as desired. The aggregated score and alerts can guide attention but should not be the sole decision-factor.
________________________________________
 ## 6. How Scoring and Logic Works (Step-by-Step) 
1.	 Compute Sub-Scores 
o	 EMA Cross:  Evaluate fast EMA > slow EMA ? +1 : fast EMA < slow EMA ? -1 : 0.
o	 VWMA Momentum:  Calculate vwma = ta.vwma(close, length), then vwma_mom = vwma - vwma . Normalize: divide by recent average absolute momentum (e.g., ta.sma(abs(vwma_mom), lookback)), clip to  .
o	 Volume Spike:  Compute vol_SMA = ta.sma(volume, len). If volume > vol_SMA * multiplier AND price moved up ≥ threshold%, assign +1; if moved down ≥ threshold%, assign -1; else 0.
o	 ATR Breakout:  Determine recent high/low over lookback. If close > high + ATR*mult, compute distance = close - (high + ATR*mult), normalize by ATR, cap at a configured maximum. Assign positive contribution. Similarly for bearish breakout below low.
o	 Higher-Timeframe Trend:  Use request.security(..., lookahead=barmerge.lookahead_off) to fetch HTF EMAs; assign +1 or -1 based on alignment.
2.	 ADX Regime Weighting 
o	Compute manual ADX: directional movements (+DM, –DM), smoothed via RMA, DI+ and DI–, then DX and ADX via RMA. If ADX ≥ threshold, market is considered “Trending”; otherwise “Ranging.”
o	If trending, trend-based contributions (EMA, VWMA, ATR, HTF) use full weight = 1.0. If ranging, use weight = ranging_weight (e.g., 0.5) to down-weight them. Volume spike stays binary ±1 (optional to change if desired).
3.	 Aggregate Raw Score 
o	Sum weighted contributions of all enabled components. Count the number of enabled components; if zero, default count = 1 to avoid division by zero.
4.	 Divergence Penalty 
o	Detect pivot highs/lows on price and corresponding RSI values, using a lookback. When price and RSI diverge (bearish or bullish divergence), check if current raw score is in the opposing direction:
	If  bearish divergence  (price higher high, RSI lower high) and raw score currently positive, subtract a penalty (e.g., 0.5).
	If  bullish divergence  (price lower low, RSI higher low) and raw score currently negative, add a penalty.
o	This reduces score magnitude to reflect weakening momentum, without flipping the trend outright.
5.	 Normalize and Smooth 
o	Normalized score = (raw_score / number_of_enabled_components) * 100. This yields a roughly   range.
o	Optional EMA smoothing of this normalized score to reduce noise.
6.	 Interpretation 
o	Sign: >0 = net bullish bias; <0 = net bearish bias; near zero = neutral.
o	Magnitude Zones: Compare |score| to thresholds (Weak, Medium, Strong) to label trend strength (e.g., “Weak Bullish Trend”, “Medium Bearish Trend”, “Strong Bullish Trend”).
o	Δ Score Histogram: The histogram bars from zero show change from previous bar’s score; positive bars indicate acceleration, negative bars indicate deceleration.
o	Confidence: Percentage of sub-indicators aligned with the score’s sign.
o	Regime: Indicates whether trend-based signals are fully weighted or down-weighted.
________________________________________
 ## 7. Oscillator Plot & Visualization: How to Read It 
 Main Score Line & Area 
The oscillator plots the aggregated score as a line, with colored fill: green above zero for bullish area, red below zero for bearish area. Horizontal reference lines at ±Weak, ±Medium, and ±Strong thresholds mark zones: crossing above +Weak suggests beginning of bullish bias, above +Medium for moderate strength, above +Strong for strong trend; similarly for bearish below negative thresholds.
 Δ Score Histogram 
If enabled, a histogram shows score - score . When positive, bars appear in green above zero, indicating accelerating bullish momentum; when negative, bars appear in red below zero, indicating decelerating or reversing momentum. The height of each bar reflects the magnitude of change in the aggregated score from the prior bar.
 Divergence Highlight Fill 
If enabled, when a pivot-based divergence is confirmed:
•	 Bullish Divergence : fill the area below zero down to –Weak threshold in green, signaling potential reversal from bearish to bullish.
•	 Bearish Divergence : fill the area above zero up to +Weak threshold in red, signaling potential reversal from bullish to bearish.
These fills appear with a lag equal to pivot lookback (the number of bars needed to confirm the pivot). They do not repaint after confirmation, but users must understand this lag.
 Trend Direction Label 
When score crosses above or below the Weak threshold, a small label appears near the score line reading “Bullish” or “Bearish.” If the score returns within ±Weak, the label “Neutral” appears. This helps quickly identify shifts at the moment they occur.
 Dashboard Panel 
In the indicator pane’s top-right, a table shows:
1.	EMA Cross status: “Bull”, “Bear”, “Flat”, or “Disabled”
2.	VWMA Momentum status: similarly
3.	Volume Spike status: “Bull”, “Bear”, “No”, or “Disabled”
4.	ATR Breakout status: “Bull”, “Bear”, “No”, or “Disabled”
5.	Higher-Timeframe Trend status: “Bull”, “Bear”, “Flat”, or “Disabled”
6.	Score: numeric value (rounded)
7.	Confidence: e.g., “80%” (colored: green for high, amber for medium, red for low)
8.	Regime: “Trending” or “Ranging” (colored accordingly)
9.	Trend Strength: textual label based on magnitude (e.g., “Medium Bullish Trend”)
10.	Gauge: a bar of blocks representing |score|/100
All rows remain visible at all times; changing Dashboard Size only scales text size (Normal, Small, Tiny).
________________________________________
 ## 8. Example Usage (Illustrative Scenario) 
 Example: BTCUSD 5 Min 
1.	 Setup:  Add “Trend Gauge  ” to your BTCUSD 5 Min chart. Defaults: EMAs (8/21), VWMA 14 with lookback 3, volume spike settings, ATR breakout 14/5, HTF = 5m (or adjust to 4H if preferred), ADX threshold 25, ranging weight 0.5, divergence RSI length 14 pivot lookback 5, penalty 0.5, smoothing length 3, thresholds Weak=20, Medium=50, Strong=80. Dashboard Size = Small.
2.	 Trend Onset:  At some point, price breaks above recent high by ATR multiple, volume spikes upward, faster EMA crosses above slower EMA, HTF EMA also bullish, and ADX (manual) ≥ threshold → aggregated score rises above +20 (Weak threshold) into +Medium zone. Dashboard shows “Bull” for EMA, VWMA, Vol Spike, ATR, HTF; Score ~+60–+70; Confidence ~100%; Regime “Trending”; Trend Strength “Medium Bullish Trend”; Gauge ~6–7 blocks. Δ Score histogram bars are green and rising, indicating accelerating bullish momentum. Trader notes the alignment.
3.	 Divergence Warning:  Later, price makes a slightly higher high but RSI fails to confirm (lower RSI high). Pivot lookback completes; the indicator highlights a bearish divergence fill above zero and subtracts a small penalty from the score, causing score to stall or retrace slightly. Dashboard still bullish but score dips toward +Weak. This warns the trader to tighten stops or take partial profits.
4.	 Trend Weakens:  Score eventually crosses below +Weak back into neutral; a “Neutral” label appears, and a “Neutral Trend” alert fires if enabled. Trader exits or avoids new long entries. If score subsequently crosses below –Weak, a “Bearish” label and alert occur.
5.	 Customization:  If the trader finds VWMA noise too frequent on this instrument, they may disable VWMA or increase lookback. If ATR breakouts are too rare, adjust ATR length or multiplier. If ADX threshold seems off, tune threshold. All these adjustments are explained in Inputs section.
6.	 Visualization:  The screenshot shows the main score oscillator with colored areas, reference lines at ±20/50/80, Δ Score histogram bars below/above zero, divergence fill highlighting potential reversal, and the dashboard table in the top-right.
  
  
________________________________________
 ## 9. Inputs Explanation 
A concise yet clear summary of inputs helps users understand and adjust:
 1. General Settings 
•	 Theme (Dark/Light):  Choose background-appropriate colors for the indicator pane.
•	 Dashboard Size (Normal/Small/Tiny):  Scales text size only; all dashboard elements remain visible.
 2. Indicator Settings 
•	 Enable EMA Cross:  Toggle on/off basic EMA alignment check.
o	Fast EMA Length and Slow EMA Length: Periods for EMAs.
•	 Enable VWMA Momentum:  Toggle VWMA momentum check.
o	VWMA Length: Period for VWMA.
o	VWMA Momentum Lookback: Bars to compare VWMA to measure momentum.
•	 Enable Volume Spike:  Toggle volume spike detection.
o	Volume SMA Length: Period to compute average volume.
o	Volume Spike Multiplier: How many times above average volume qualifies as spike.
o	Min Price Move (%): Minimum percent change in price during spike to qualify as bullish or bearish.
•	 Enable ATR Breakout:  Toggle ATR breakout detection.
o	ATR Length: Period for ATR.
o	Breakout Lookback: Bars to look back for recent highs/lows.
o	ATR Multiplier: Multiplier for breakout threshold.
•	 Enable Higher Timeframe Trend:  Toggle HTF EMA alignment.
o	Higher Timeframe: E.g., “5” for 5-minute when on 1-minute chart, or “60” for 5 Min when on 15m, etc. Uses lookahead_off.
•	 Enable ADX Regime Filter:  Toggles regime-based weighting.
o	ADX Length: Period for manual ADX calculation.
o	ADX Threshold: Value above which market considered trending.
o	Ranging Weight Multiplier: Weight applied to trend components when ADX < threshold (e.g., 0.5).
•	 Scale VWMA Momentum:  Toggle normalization of VWMA momentum magnitude.
o	VWMA Mom Scale Lookback: Period for average absolute VWMA momentum.
•	 Scale ATR Breakout Strength:  Toggle normalization of breakout distance by ATR.
o	ATR Scale Cap: Maximum multiple of ATR used for breakout strength.
•	 Enable Price-RSI Divergence:  Toggle divergence detection.
o	RSI Length for Divergence: Period for RSI.
o	Pivot Lookback for Divergence: Bars on each side to identify pivot high/low.
o	Divergence Penalty: Amount to subtract/add to score when divergence detected (e.g., 0.5).
 3. Score Settings 
•	 Smooth Score:  Toggle EMA smoothing of normalized score.
•	 Score Smoothing Length:  Period for smoothing EMA.
•	 Weak Threshold:  Absolute score value under which trend is considered weak or neutral.
•	 Medium Threshold:  Score above Weak but below Medium is moderate.
•	 Strong Threshold:  Score above this indicates strong trend.
 4. Visualization Settings 
•	 Show Δ Score Histogram:  Toggle display of the bar-to-bar change in score as a histogram. Default true.
•	 Show Divergence Fill:  Toggle background fill highlighting confirmed divergences. Default true.
Each input has a tooltip in the code.
________________________________________
 ## 10. Limitations, Repaint Notes, and Disclaimers 
 10.1. Repaint & Lag Considerations 
•	 Pivot-Based Divergence Lag:  The divergence detection uses ta.pivothigh / ta.pivotlow with a specified lookback. By design, a pivot is only confirmed after the lookback number of bars. As a result:
o	Divergence labels or fills appear with a delay equal to the pivot lookback.
o	Once the pivot is confirmed and the divergence is detected, the fill/label does not repaint thereafter, but you must understand and accept this lag.
o	Users should not treat divergence highlights as predictive signals without additional confirmation, because they appear after the pivot has fully formed.
•	 Higher-Timeframe EMA Alignment:  Uses request.security(..., lookahead=barmerge.lookahead_off), so no future data from the higher timeframe is used. This avoids lookahead bias and ensures signals are based only on completed higher-timeframe bars.
•	 No Future Data:  All calculations are designed to avoid using future information. For example, manual ADX uses RMA on past data; security calls use lookahead_off.
 10.2. Market & Noise Considerations 
•	In very choppy or low-liquidity markets, some components (e.g., volume spikes or VWMA momentum) may be noisy. Users can disable or adjust those components’ parameters.
•	On extremely low timeframes, noise may dominate; consider smoothing lengths or disabling certain features.
•	On very high timeframes, pivots and breakouts occur less frequently; adjust lookbacks accordingly to avoid sparse signals.
 10.3. Not a Standalone Trading System 
•	This is an indicator, not a complete trading strategy. It provides signals and context but does not manage entries, exits, position sizing, or risk management.
•	Users must combine it with their own analysis, money management, and confirmations (e.g., price patterns, support/resistance, fundamental context).
•	No guarantees: past behavior does not guarantee future performance.
 10.4. Disclaimers 
•	 Educational Purposes Only:  The script is provided as-is for educational and informational purposes. It does not constitute financial, investment, or trading advice.
•	 Use at Your Own Risk:  Trading involves risk of loss. Users should thoroughly test and use proper risk management.
•	 No Guarantees:  The author   is not responsible for trading outcomes based on this indicator.
•	 License:  Published under Mozilla Public License 2.0; code is open for viewing and modification under MPL terms.
________________________________________
 ## 11. Alerts 
•	The indicator defines three alert conditions:
1.	 Bullish Trend:  when the aggregated score crosses above the Weak threshold.
2.	 Bearish Trend:  when the score crosses below the negative Weak threshold.
3.	 Neutral Trend:  when the score returns within ±Weak after being outside.
Good luck
– BullByte
Dskyz (DAFE) Adaptive Regime - Quant Machine ProDskyz (DAFE) Adaptive Regime - Quant Machine Pro:
Buckle up for the Dskyz (DAFE) Adaptive Regime - Quant Machine Pro, is a strategy that’s your ultimate edge for conquering futures markets like ES, MES, NQ, and MNQ. This isn’t just another script—it’s a quant-grade powerhouse, crafted with precision to adapt to market regimes, deliver multi-factor signals, and protect your capital with futures-tuned risk management. With its shimmering DAFE visuals, dual dashboards, and glowing watermark, it turns your charts into a cyberpunk command center, making trading as thrilling as it is profitable.
Unlike generic scripts clogging up the space, the Adaptive Regime is a DAFE original, built from the ground up to tackle the chaos of futures trading. It identifies market regimes (Trending, Range, Volatile, Quiet) using ADX, Bollinger Bands, and HTF indicators, then fires trades based on a weighted scoring system that blends candlestick patterns, RSI, MACD, and more. Add in dynamic stops, trailing exits, and a 5% drawdown circuit breaker, and you’ve got a system that’s as safe as it is aggressive. Whether you’re a newbie or a prop desk pro, this strat’s your ticket to outsmarting the markets. Let’s break down every detail and see why it’s a must-have.
Why Traders Need This Strategy
Futures markets are a gauntlet—fast moves, volatility spikes (like the April 28, 2025 NQ 1k-point drop), and institutional traps that punish the unprepared. Meanwhile, platforms are flooded with low-effort scripts that recycle old ideas with zero innovation. The Adaptive Regime stands tall, offering:
Adaptive Intelligence: Detects market regimes (Trending, Range, Volatile, Quiet) to optimize signals, unlike one-size-fits-all scripts.
Multi-Factor Precision: Combines candlestick patterns, MA trends, RSI, MACD, volume, and HTF confirmation for high-probability trades.
Futures-Optimized Risk: Calculates position sizes based on $ risk (default: $300), with ATR or fixed stops/TPs tailored for ES/MES.
Bulletproof Safety: 5% daily drawdown circuit breaker and trailing stops keep your account intact, even in chaos.
DAFE Visual Mastery: Pulsing Bollinger Band fills, dynamic SL/TP lines, and dual dashboards (metrics + position) make signals crystal-clear and charts a work of art.
Original Craftsmanship: A DAFE creation, built with community passion, not a rehashed clone of generic code.
Traders need this because it’s a complete, adaptive system that blends quant smarts, user-friendly design, and DAFE flair. It’s your edge to trade with confidence, cut through market noise, and leave the copycats in the dust.
Strategy Components
1. Market Regime Detection
The strategy’s brain is its ability to classify market conditions into five regimes, ensuring signals match the environment.
How It Works:
Trending (Regime 1): ADX > 20, fast/slow EMA spread > 0.3x ATR, HTF RSI > 50 or MACD bullish (htf_trend_bull/bear).
Range (Regime 2): ADX < 25, price range < 3% of close, no HTF trend.
Volatile (Regime 3): BB width > 1.5x avg, ATR > 1.2x avg, HTF RSI overbought/oversold.
Quiet (Regime 4): BB width < 0.8x avg, ATR < 0.9x avg.
Other (Regime 5): Default for unclear conditions.
Indicators: ADX (14), BB width (20), ATR (14, 50-bar SMA), HTF RSI (14, daily default), HTF MACD (12,26,9).
Why It’s Brilliant:
Regime detection adapts signals to market context, boosting win rates in trending or volatile conditions.
HTF RSI/MACD add a big-picture filter, rare in basic scripts.
Visualized via gradient background (green for Trending, orange for Range, red for Volatile, gray for Quiet, navy for Other).
2. Multi-Factor Signal Scoring
Entries are driven by a weighted scoring system that combines candlestick patterns, trend, momentum, and volume for robust signals.
Candlestick Patterns:
Bullish: Engulfing (0.5), hammer (0.4 in Range, 0.2 else), morning star (0.2), piercing (0.2), double bottom (0.3 in Volatile, 0.15 else). Must be near support (low ≤ 1.01x 20-bar low) with volume spike (>1.5x 20-bar avg).
Bearish: Engulfing (0.5), shooting star (0.4 in Range, 0.2 else), evening star (0.2), dark cloud (0.2), double top (0.3 in Volatile, 0.15 else). Must be near resistance (high ≥ 0.99x 20-bar high) with volume spike.
Logic: Patterns are weighted higher in specific regimes (e.g., hammer in Range, double bottom in Volatile).
Additional Factors:
Trend: Fast EMA (20) > slow EMA (50) + 0.5x ATR (trend_bull, +0.2); opposite for trend_bear.
RSI: RSI (14) < 30 (rsi_bull, +0.15); > 70 (rsi_bear, +0.15).
MACD: MACD line > signal (12,26,9, macd_bull, +0.15); opposite for macd_bear.
Volume: ATR > 1.2x 50-bar avg (vol_expansion, +0.1).
HTF Confirmation: HTF RSI < 70 and MACD bullish (htf_bull_confirm, +0.2); RSI > 30 and MACD bearish (htf_bear_confirm, +0.2).
Scoring:
bull_score = sum of bullish factors; bear_score = sum of bearish. Entry requires score ≥ 1.0.
Example: Bullish engulfing (0.5) + trend_bull (0.2) + rsi_bull (0.15) + htf_bull_confirm (0.2) = 1.05, triggers long.
Why It’s Brilliant:
Multi-factor scoring ensures signals are confirmed by multiple market dynamics, reducing false positives.
Regime-specific weights make patterns more relevant (e.g., hammers shine in Range markets).
HTF confirmation aligns with the big picture, a quant edge over simplistic scripts.
3. Futures-Tuned Risk Management
The risk system is built for futures, calculating position sizes based on $ risk and offering flexible stops/TPs.
Position Sizing:
Logic: Risk per trade (default: $300) ÷ (stop distance in points * point value) = contracts, capped at max_contracts (default: 5). Point value = tick value (e.g., $12.5 for ES) * ticks per point (4) * contract multiplier (1 for ES, 0.1 for MES).
Example: $300 risk, 8-point stop, ES ($50/point) → 0.75 contracts, rounded to 1.
Impact: Precise sizing prevents over-leverage, critical for micro contracts like MES.
Stops and Take-Profits:
Fixed: Default stop = 8 points, TP = 16 points (2:1 reward/risk).
ATR-Based: Stop = 1.5x ATR (default), TP = 3x ATR, enabled via use_atr_for_stops.
Logic: Stops set at swing low/high ± stop distance; TPs at 2x stop distance from entry.
Impact: ATR stops adapt to volatility, while fixed stops suit stable markets.
Trailing Stops:
Logic: Activates at 50% of TP distance. Trails at close ± 1.5x ATR (atr_multiplier). Longs: max(trail_stop_long, close - ATR * 1.5); shorts: min(trail_stop_short, close + ATR * 1.5).
Impact: Locks in profits during trends, a game-changer in volatile sessions.
Circuit Breaker:
Logic: Pauses trading if daily drawdown > 5% (daily_drawdown = (max_equity - equity) / max_equity).
Impact: Protects capital during black swan events (e.g., April 27, 2025 ES slippage).
Why It’s Brilliant:
Futures-specific inputs (tick value, multiplier) make it plug-and-play for ES/MES.
Trailing stops and circuit breaker add pro-level safety, rare in off-the-shelf scripts.
Flexible stops (ATR or fixed) suit different trading styles.
4. Trade Entry and Exit Logic
Entries and exits are precise, driven by bull_score/bear_score and protected by drawdown checks.
Entry Conditions:
Long: bull_score ≥ 1.0, no position (position_size <= 0), drawdown < 5% (not pause_trading). Calculates contracts, sets stop at swing low - stop points, TP at 2x stop distance.
Short: bear_score ≥ 1.0, position_size >= 0, drawdown < 5%. Stop at swing high + stop points, TP at 2x stop distance.
Logic: Tracks entry_regime for PNL arrays. Closes opposite positions before entering.
Exit Conditions:
Stop-Loss/Take-Profit: Hits stop or TP (strategy.exit).
Trailing Stop: Activates at 50% TP, trails by ATR * 1.5.
Emergency Exit: Closes if price breaches stop (close < long_stop_price or close > short_stop_price).
Reset: Clears stop/TP prices when flat (position_size = 0).
Why It’s Brilliant:
Score-based entries ensure multi-factor confirmation, filtering out weak signals.
Trailing stops maximize profits in trends, unlike static exits in basic scripts.
Emergency exits add an extra safety layer, critical for futures volatility.
5. DAFE Visuals
The visuals are pure DAFE magic, blending function with cyberpunk flair to make signals intuitive and charts stunning.
Shimmering Bollinger Band Fill:
Display: BB basis (20, white), upper/lower (green/red, 45% transparent). Fill pulses (30–50 alpha) by regime, with glow (60–95 alpha) near bands (close ≥ 0.995x upper or ≤ 1.005x lower).
Purpose: Highlights volatility and key levels with a futuristic glow.
Visuals make complex regimes and signals instantly clear, even for newbies.
Pulsing effects and regime-specific colors add a DAFE signature, setting it apart from generic scripts.
BB glow emphasizes tradeable levels, enhancing decision-making.
Chart Background (Regime Heatmap):
Green — Trending Market: Strong, sustained price movement in one direction. The market is in a trend phase—momentum follows through.
Orange — Range-Bound: Market is consolidating or moving sideways, with no clear up/down trend. Great for mean reversion setups.
Red — Volatile Regime: High volatility, heightened risk, and larger/faster price swings—trade with caution.
Gray — Quiet/Low Volatility: Market is calm and inactive, with small moves—often poor conditions for most strategies.
Navy — Other/Neutral: Regime is uncertain or mixed; signals may be less reliable.
Bollinger Bands Glow (Dynamic Fill):
Neon Red Glow — Warning!: Price is near or breaking above the upper band; momentum is overstretched, watch for overbought conditions or reversals.
Bright Green Glow — Opportunity!: Price is near or breaking below the lower band; market could be oversold, prime for bounce or reversal.
Trend Green Fill — Trending Regime: Fills between bands with green when the market is trending, showing clear momentum.
Gold/Yellow Fill — Range Regime: Fills with gold/aqua in range conditions, showing the market is sideways/oscillating.
Magenta/Red Fill — Volatility Spike: Fills with vivid magenta/red during highly volatile regimes.
Blue Fill — Neutral/Quiet: A soft blue glow for other or uncertain market states.
Moving Averages:
Display: Blue fast EMA (20), red slow EMA (50), 2px.
Purpose: Shows trend direction, with trend_dir requiring ATR-scaled spread.
Dynamic SL/TP Lines:
Display: Pulsing colors (red SL, green TP for Trending; yellow/orange for Range, etc.), 3px, with pulse_alpha for shimmer.
Purpose: Tracks stops/TPs in real-time, color-coded by regime.
6. Dual Dashboards
Two dashboards deliver real-time insights, making the strat a quant command center.
Bottom-Left Metrics Dashboard (2x13):
Metrics: Mode (Active/Paused), trend (Bullish/Bearish/Neutral), ATR, ATR avg, volume spike (YES/NO), RSI (value + Oversold/Overbought/Neutral), HTF RSI, HTF trend, last signal (Buy/Sell/None), regime, bull score.
Display: Black (29% transparent), purple title, color-coded (green for bullish, red for bearish).
Purpose: Consolidates market context and signal strength.
Top-Right Position Dashboard (2x7):
Metrics: Regime, position side (Long/Short/None), position PNL ($), SL, TP, daily PNL ($).
Display: Black (29% transparent), purple title, color-coded (lime for Long, red for Short).
Purpose: Tracks live trades and profitability.
Why It’s Brilliant:
Dual dashboards cover market context and trade status, a rare feature.
Color-coding and concise metrics guide beginners (e.g., green “Buy” = go).
Real-time PNL and SL/TP visibility empower disciplined trading.
7. Performance Tracking
Logic: Arrays (regime_pnl_long/short, regime_win/loss_long/short) track PNL and win/loss by regime (1–5). Updated on trade close (barstate.isconfirmed).
Purpose: Prepares for future adaptive thresholds (e.g., adjust bull_score min based on regime performance).
Why It’s Brilliant: Lays the groundwork for self-optimizing logic, a quant edge over static scripts.
Key Features
Regime-Adaptive: Optimizes signals for Trending, Range, Volatile, Quiet markets.
Futures-Optimized: Precise sizing for ES/MES with tick-based risk inputs.
Multi-Factor Signals: Candlestick patterns, RSI, MACD, and HTF confirmation for robust entries.
Dynamic Exits: ATR/fixed stops, 2:1 TPs, and trailing stops maximize profits.
Safe and Smart: 5% drawdown breaker and emergency exits protect capital.
DAFE Visuals: Shimmering BB fill, pulsing SL/TP, and dual dashboards.
Backtest-Ready: Fixed qty and tick calc for accurate historical testing.
How to Use
Add to Chart: Load on a 5min ES/MES chart in TradingView.
Configure Inputs: Set instrument (ES/MES), tick value ($12.5/$1.25), multiplier (1/0.1), risk ($300 default). Enable ATR stops for volatility.
Monitor Dashboards: Bottom-left for regime/signals, top-right for position/PNL.
Backtest: Run in strategy tester to compare regimes.
Live Trade: Connect to Tradovate or similar. Watch for slippage (e.g., April 27, 2025 ES issues).
Replay Test: Try April 28, 2025 NQ drop to see regime shifts and stops.
Disclaimer
Trading futures involves significant risk of loss and is not suitable for all investors. Past performance does not guarantee future results. Backtest results may differ from live trading due to slippage, fees, or market conditions. Use this strategy at your own risk, and consult a financial advisor before trading. Dskyz (DAFE) Trading Systems is not responsible for any losses incurred.
Backtesting:
Frame: 2023-09-20 - 2025-04-29
Slippage: 3
Fee Typical Range (per side, per contract)
CME Exchange $1.14 – $1.20
Clearing $0.10 – $0.30
NFA Regulatory $0.02
Firm/Broker Commis. $0.25 – $0.80 (retail prop)
TOTAL $1.60 – $2.30 per side
Round Turn: (enter+exit) = $3.20 – $4.60 per contract
Final Notes
The Dskyz (DAFE) Adaptive Regime - Quant Machine Pro is more than a strategy—it’s a revolution. Crafted with DAFE’s signature precision, it rises above generic scripts with adaptive regimes, quant-grade signals, and visuals that make trading a thrill. Whether you’re scalping MES or swinging ES, this system empowers you to navigate markets with confidence and style. Join the DAFE crew, light up your charts, and let’s dominate the futures game!
(This publishing will most likely be taken down do to some miscellaneous rule about properly displaying charting symbols, or whatever. Once I've identified what part of the publishing they want to pick on, I'll adjust and repost.)
Use it with discipline. Use it with clarity. Trade smarter.
**I will continue to release incredible strategies and indicators until I turn this into a brand or until someone offers me a contract.
Created by Dskyz, powered by DAFE Trading Systems. Trade smart, trade bold.
Combined EMA Technical AnalysisThis script is written in Pine Script (version 5) for TradingView and creates a comprehensive technical analysis indicator called "Combined EMA Technical Analysis." It overlays multiple technical indicators on a price chart, including Exponential Moving Averages (EMAs), VWAP, MACD, PSAR, RSI, Bollinger Bands, ADX, and external data from the S&P 500 (SPX) and VIX indices. The script also provides visual cues through colors, shapes, and a customizable table to help traders interpret market conditions.
Here’s a breakdown of the script:
---
### **1. Purpose**
- The script combines several popular technical indicators to analyze price trends, momentum, volatility, and market sentiment.
- It uses color coding (green for bullish, red for bearish, gray/white for neutral) and a table to display key information.
---
### **2. Custom Colors**
- Defines custom RGB colors for bullish (`customGreen`), bearish (`customRed`), and neutral (`neutralGray`) signals to enhance visual clarity.
---
### **3. User Inputs**
- **EMA Colors**: Users can customize the colors of five EMAs (8, 20, 9, 21, 50 periods).
- **MACD Settings**: Adjustable short length (12), long length (26), and signal length (9).
- **RSI Settings**: Adjustable length (14).
- **Bollinger Bands Settings**: Length (20), multiplier (2), and proximity threshold (0.1% of band width).
- **ADX Settings**: Adjustable length (14).
- **Table Settings**: Position (e.g., "Bottom Right") and text size (e.g., "Small").
---
### **4. Indicator Calculations**
#### **Exponential Moving Averages (EMAs)**
- Calculates five EMAs: 8, 20, 9, 21, and 50 periods based on the closing price.
- Used to identify short-term and long-term trends.
#### **Volume Weighted Average Price (VWAP)**
- Resets daily and calculates the average price weighted by volume.
- Color-coded: green if price > VWAP (bullish), red if price < VWAP (bearish), white if neutral.
#### **MACD (Moving Average Convergence Divergence)**
- Uses short (12) and long (26) EMAs to compute the MACD line, with a 9-period signal line.
- Displays "Bullish" (green) if MACD > signal, "Bearish" (red) if MACD < signal.
#### **Parabolic SAR (PSAR)**
- Calculated with acceleration factors (start: 0.02, increment: 0.02, max: 0.2).
- Indicates trend direction: green if price > PSAR (bullish), red if price < PSAR (bearish).
#### **Relative Strength Index (RSI)**
- Measures momentum over 14 periods.
- Highlighted in green if > 70 (overbought), red if < 30 (oversold), white otherwise.
#### **Bollinger Bands (BB)**
- Uses a 20-period SMA with a 2-standard-deviation multiplier.
- Color-coded based on price position:
  - Green: Above upper band or close to it.
  - Red: Below lower band or close to it.
  - Gray: Neutral (within bands).
#### **Average Directional Index (ADX)**
- Manually calculates ADX to measure trend strength:
  - Strong trend: ADX > 25.
  - Very strong trend: ADX > 50.
  - Direction: Bullish if +DI > -DI, bearish if -DI > +DI.
#### **EMA Crosses**
- Detects bullish (crossover) and bearish (crossunder) events for:
  - EMA 9 vs. EMA 21.
  - EMA 8 vs. EMA 20.
- Visualized with green (bullish) or red (bearish) circles.
#### **SPX and VIX Data**
- Fetches daily closing prices for the S&P 500 (SPX) and VIX (volatility index).
- SPX trend: Bullish if EMA 9 > EMA 21, bearish if EMA 9 < EMA 21.
- VIX levels: High (> 25, fear), Low (< 15, stability).
- VIX color: Green if SPX bullish and VIX low, red if SPX bearish and VIX high, white otherwise.
---
### **5. Visual Outputs**
#### **Plots**
- EMAs, VWAP, and PSAR are plotted on the chart with their respective colors.
- EMA crosses are marked with circles (green for bullish, red for bearish).
#### **Table**
- Displays a summary of indicators in a customizable position and size.
- Indicators shown (if enabled):
  - EMA 8/20, 9/21, 50: Green dot if bullish, red if bearish.
  - VWAP: Green if price > VWAP, red if price < VWAP.
  - MACD: Green if bullish, red if bearish.
  - MACD Zero: Green if MACD > 0, red if MACD < 0.
  - PSAR: Green if price > PSAR, red if price < PSAR.
  - ADX: Arrows for very strong trends (↑/↓), dots for weaker trends, colored by direction.
  - Bollinger Bands: Arrows (↑/↓) or dots based on price position.
  - RSI: Numeric value, colored by overbought/oversold levels.
  - VIX: Numeric value, colored based on SPX trend and VIX level.
---
### **6. Alerts**
- Triggers alerts for EMA 8/20 crosses:
  - Bullish: "EMA 8/20 Bullish Cross on Candle Close!"
  - Bearish: "EMA 8/20 Bearish Cross on Candle Close!"
---
### **7. Key Features**
- **Flexibility**: Users can toggle indicators on/off in the table and adjust parameters.
- **Visual Clarity**: Consistent use of green (bullish), red (bearish), and neutral colors.
- **Comprehensive**: Combines trend, momentum, volatility, and market sentiment indicators.
---
### **How to Use**
1. Add the script to TradingView.
2. Customize inputs (colors, lengths, table position) as needed.
3. Interpret the chart and table:
   - Green signals suggest bullish conditions.
   - Red signals suggest bearish conditions.
   - Neutral signals indicate indecision or consolidation.
4. Set up alerts for EMA crosses to catch trend changes.
This script is ideal for traders who want a multi-indicator dashboard to monitor price action and market conditions efficiently.
Volume Standard Deviation Alert GusPurpose
The script detects and alerts traders when the volume of a trading asset significantly exceeds a calculated threshold based on the standard deviation of volume over a specified lookback period. It optionally filters these alerts based on whether the price action is bullish or bearish.
Key Components
Inputs
lookback (default: 20)
The number of bars to consider when calculating the moving average and standard deviation of volume.
stdDevFactor (default: 2.0)
The multiplier for the standard deviation to determine the threshold for a volume spike.
alertOnClose (default: true)
Determines whether alerts should only be triggered after the bar has closed.
checkBullBear (default: false)
Enables filtering of alerts based on the bullishness or bearishness of the bar.
Calculations
volSMA
The simple moving average (SMA) of the volume over the lookback period.
volStd
The standard deviation of the volume over the lookback period.
threshold
The alert threshold is calculated as:
Threshold
=
volSMA
+
(
stdDevFactor
×
volStd
)
Threshold=volSMA+(stdDevFactor×volStd)
isBullish & isBearish
Determines whether the current bar is bullish (close > open) or bearish (close < open).
volumeSpikeCondition
A condition that triggers when the current volume exceeds the calculated threshold.
bullishCondition & bearishCondition
Refines the spike condition by requiring the bar to be bullish or bearish when checkBullBear is enabled.
finalCondition
The ultimate alert condition based on the user’s preference for bullish/bearish filtering.
finalTrigger
Ensures the alert only triggers at bar close if alertOnClose is set to true.
Visualization
Plots the SMA of the volume (volSMA) and the threshold line (threshold), helping traders visually understand the conditions.
Histograms the current volume and colors the bars:
Red: Volume exceeds the threshold.
Blue: Volume is below the threshold.
Alerts
The script generates an alert message when the finalTrigger condition is met:
"Bullish Volume Spike!" if the bar is bullish.
"Bearish Volume Spike!" if the bar is bearish.
"High Volume Spike!" if no bull/bear filter is applied.
Alerts are sent using alert() with the message and set to trigger once per bar close.
Usage
Traders can use this script to identify unusual volume activity, which often precedes significant price movements.
Customizability allows traders to tune the lookback period, standard deviation multiplier, and whether to filter for bullish/bearish spikes.
Visual and audible cues help in identifying important market events in real time.
This indicator is particularly useful for spotting market breakouts or breakdowns driven by high trading activity.
Custom RSI & MACD Momentum Entry SignalsIndicator Explanation: Custom RSI & MACD Momentum Entry Signals
Introduction
The "Custom RSI & MACD Momentum Entry Signals" indicator combines the Relative Strength Index (RSI) and the Moving Average Convergence Divergence (MACD) to generate precise long and short entry signals. This indicator offers a powerful combination of overbought/oversold zones, momentum analysis, and RSI-EMA crossovers to assist traders in making better decisions.
How the Indicator Works
1. RSI Calculation and EMA
    The RSI is calculated based on the closing price with an adjustable period (default: 14).
    An Exponential Moving Average (EMA) of the RSI (default: 9) is plotted to identify RSI trend changes.
    When the RSI crosses its EMA upwards, it signals a bullish impulse. Conversely, a downward cross indicates a bearish impulse.
2. MACD Calculation and Momentum Shifts
    The MACD line is derived from the difference between a fast EMA (default: 12) and a slow EMA (default: 26).
    The Signal line is the EMA of the MACD line (default: 9).
    The MACD histogram represents the difference between the MACD line and the Signal line.
    Momentum shifts are detected as follows:
        Weakening Bearish: Histogram is negative but increasing (less bearish pressure).
        Strengthening Bullish: Histogram is positive and rising.
        Weakening Bullish: Histogram is positive but decreasing.
        Strengthening Bearish: Histogram is negative and falling.
Signal Generation
Long Signals
A Long signal is triggered when all of the following conditions are met:
    The RSI was previously below 30 (oversold condition).
    MACD momentum shifts from "strengthening bearish" to "weakening bearish" or turns bullish.
    The RSI crosses its EMA upwards.
A green upward arrow is displayed below the bar, and the background is lightly shaded green for additional visualization.
Short Signals
A Short signal is triggered when all of the following conditions are met:
    The RSI was previously above 70 (overbought condition).
    MACD momentum shifts from "strengthening bullish" to "weakening bullish" or turns bearish.
    The RSI crosses its EMA downwards.
A red downward arrow is displayed above the bar, and the background is lightly shaded red for additional visualization.
Visual Elements
    RSI and EMA:
        The RSI is shown in purple.
        The RSI EMA is shown in blue.
        Horizontal lines at 30 (oversold) and 70 (overbought) provide additional context.
    MACD:
        The MACD line is displayed in blue.
        The Signal line is displayed in orange.
        The zero line is added for easier interpretation.
    Signals:
        Green arrows: Long signals.
        Red arrows: Short signals.
        Background color: Light green for long conditions, light red for short conditions.
Use Cases
This indicator is ideal for:
    Trend Followers: Combining RSI and MACD allows traders to identify entry points during impulsive trend shifts.
    Swing Traders: Long and short signals can be used at reversal points to capture short-term price movements.
    Momentum Traders: By considering MACD momentum, the indicator provides additional confidence in signal generation.
Customizable Settings
The indicator provides flexible input options:
    RSI Period (default: 14)
    RSI EMA Period (default: 9)
    MACD Parameters: Fast, slow, and signal EMAs can be adjusted.
Conclusion
The Custom RSI & MACD Momentum Entry Signals indicator is a powerful tool for traders looking to combine RSI and MACD to identify high-probability entry signals. With clear visualization and precise signal generation, traders can make decisions more efficiently and capitalize on market movements.
Multi Timeframe Trend StrengthThis code is an advancement of my previous percentile-based trend strength. It follows the same concept, except this code display the trend and trend strength in multiple timeframe (1 min, 5 min, 15 min, 1hr and 4hr).
This gives an indication of the trend is evolving and allows to see how short-term trend matches with the long-term trend.
How it works: 
The script assesses trend strength through percentile values derived from high and low prices across various time periods. It categorizes the current trend as either Bullish, Bearish, or N/A (No Trend) with the following steps:
Percentile Calculations: The code calculates the 75th percentile of high prices (e.g., percentile_13H) and the 25th percentile of low prices (e.g., percentile_13L) for specified Fibonacci-based periods (13, 21, 34, 55, 89, and 144). These percentiles serve as thresholds for identifying strong trends.
Calculate Highest High and Lowest Low: It computes the highest high (75th percentile high price of the longest period) and lowest low (25th percentile low price of the longest period), referred to as highest_high and lowest_low. These values establish critical price levels.
Trend Strength Conditions: For each percentile and period, the code checks if the percentile exceeds the highest high (trendBull) or falls below the lowest low (trendBear). These conditions gauge the strength of bullish and bearish trends.
Count Bull and Count Bear: Variables countBull and countBear tally the number of bullish and bearish conditions met, helping assess trend strength.
Weak Bull and Weak Bear Count: The code calculates weak bullish and bearish conditions, occurring when percentiles fall within the range defined by highest_high and lowest_low but don't meet strong trend criteria.
Bull Strength and Bear Strength: bullStrength and bearStrength are calculated based on counts of bullish, bearish, weak bullish, and weak bearish conditions, representing overall trend strength.
Strong Bull and Bear Conditions: These conditions arise when the 75th percentile of high prices (bull conditions) or the 25th percentile of low prices (bear conditions) surpass or dip below the highest high or lowest low, respectively, for the specified period. Strong conditions indicate robust trends with significant price movements.
Weak Bull and Bear Conditions: Weak conditions occur when percentiles fall within the range between highest_high and lowest_low, suggesting some bullish or bearish tendencies without reaching extreme levels. These imply less decisive trends.
Current Trend Identification: The current trend is determined by comparing bullStrength and bearStrength. A greater bullStrength indicates a Bull trend, greater bearStrength implies a Bear trend, and equal values denote No Trend (N/A).
Percentile Based Trend StrengthThe "Percentile Based Trend Strength" (PBTS) calculates trend strength based on percentile values of high and low prices for various length periods and then identifies the current trend as either Bullish, Bearish, or N/A (No Trend). Here's a step-by-step explanation of the code: 
Percentile Calculations:
For each specified length period (13, 21, 34, 55, 89, and 144 - Fibonacci numbers), the code calculates the 75th percentile of high prices (e.g., percentile_13H) and the 25th percentile of low prices (e.g., percentile_13L). These percentiles represent levels that prices need to exceed or fall below to indicate a strong trend.
Calculate Highest High and Lowest Low:
The highest high (75th percentile high price of longest length) and lowest low (25th percentile low price of longest length) for the longest length period (144) are calculated as highest_high and lowest_low. These values represent  threshold price levels .
Trend Strength Conditions:
The code calculates various conditions to determine trend strength. For each percentile value and each length period, it checks if the percentile value is greater than the highest high (trendBull) or less than the lowest low (trendBear). These conditions are used to assess the strength of the bullish and bearish trends.
Count Bull and Count Bear:
The countBull and countBear variables count the number of bullish and bearish conditions met, respectively. These counts help evaluate trend strength.
Weak Bull and Weak Bear Count:
The code calculates the number of weak bullish and bearish conditions. Weak conditions occur when a percentile value falls within the range defined by the highest high and lowest low but doesn't meet the strong trend criteria.
Bull Strength and Bear Strength:
bullStrength and bearStrength are calculated based on the counts of bullish, bearish, weak bullish, and weak bearish conditions. These values represent the overall strength of the bullish and bearish trends.
Strong Bull and Bear Conditions:
These conditions occur when the 75th percentile of high prices (for bull conditions) or the 25th percentile of low prices (for bear conditions) exceeds or falls below the highest high or lowest low, respectively, for the specified length period.
Strong bull conditions indicate a strong upward trend, while strong bear conditions indicate a strong downward trend.
Strong conditions are indicative of more significant price movements and are considered as primary signals of trend strength.
Weak Bull and Bear Conditions:
Weak bull and bear conditions are more nuanced. They occur when the 75th percentile of high prices (for weak bull conditions) or the 25th percentile of low prices (for weak bear conditions) falls within the range defined by the highest high and lowest low for the specified length period.
In other words, prices are not strong enough to reach the extreme levels represented by the highest high or lowest low, but they still exhibit some bullish or bearish tendencies within that range.
Weak conditions suggest a less robust trend. They may indicate that while there is some bias toward a bullish or bearish trend, it is not as strong or decisive as in the case of strong conditions.
Current Trend Identification:
The current trend is determined by comparing bullStrength and bearStrength. If bullStrength is greater, it's considered a Bull trend; if bearStrength is greater, it's a Bear trend. If they are equal, the trend is identified as N/A (No Trend).
Displaying Trend Information:
The code creates a table to display the current trend, reversal probability (strength), count of bullish and bearish conditions, weak bullish and weak bearish counts, and colors the text accordingly.
Plotting Percentiles:
Finally, the code plots the percentile lines for visualization, with 20% transparency. It also plots the highest high and lowest low lines (75th and 25th percentile of the longest length 144) using their original colors.
In summary, this indicator calculates trend strength based on percentile levels of high and low prices for different length periods. It then counts the number of bullish and bearish conditions, factors in weak conditions, and compares the strengths to identify the current trend as Bullish, Bearish, or No Trend. It provides a table with trend information and visualizes percentile lines on the chart.
CandlestickPatternsLibrary   "CandlestickPatterns" 
This library provides a wide range of candlestick patterns, and available for user to call each pattern individually. It's a comprehensive and common tool designed for traders seeking to raise their technical analysis, and it may help users identify key turning of price action in financial instruments. Credit to public technical “*All Candlestick Patterns*” indicator.
 abandonedBaby(order, d1) 
  The "Abandoned Baby" candlestick pattern is a bullish/bearish pattern consists of three candles.
  Parameters:
     order (simple string) : (simple string) Pattern order type "bull" or "bear".
     d1 (simple float) : (simple float)  Previous candle's body percentage out of candle range. Optional argument, default is 5.
 darkCloudCover(c1, n) 
  The "Dark Cloud Cover" is a bearish pattern consists of two candles.
  Parameters:
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 doji(d0) 
  The "Doji" is neither bullish or bearish consists of one candles.
  Parameters:
     d0 (simple float) : (simple float)  Current candle's body percentage out of candle range. Optional argument, default is 5.
 dojiStar(order, c1, n, d0) 
  The "Doji Star" is a bullish/bearish pattern consists of two candles.
  Parameters:
     order (simple string) : (simple string) Pattern order type "bull" or "bear" .
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
     d0 (simple float) : (simple float) Current candle's body percentage out of candle range. Optional argument, default is 5.
 downsideTasukiGap(c2, c1, n) 
  The "Downside Tasuki Gap" is a bearish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 dragonflyDoji(d0) 
  The "Dragon Fly Doji" is a bullish pattern consists of one candle.
  Parameters:
     d0 (simple float) : (simple float)  Current candle's body percentage out of candle range. Optional argument, default is 5.
 engulfing(order, c1, c0, n) 
  The "Engulfing" is a bullish/bearish pattern consists of two candles.
  Parameters:
     order (simple string) : (simple string) Pattern order type "bull" or "bear".
     c1 (simple bool) : (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 eveningDojiStar(c2, c0, d1, n) 
  The "Evening Doji Star" is a bearish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool) Before previous candle's body must be higher than average, default is true.
     c0 (simple bool) : (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
     d1 (simple float) : (simple float) Previous candle's body percentage out of candle range. Optional argument, default is 5.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 eveningStar(c2, c1, c0, n) 
  The "Evening Star" is a bearish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 fallingThreeMethods(c4, c3, c2, c1, c0, n) 
  The "Falling Three Methods" is a bearish pattern consists of five candles.
  Parameters:
     c4 (simple bool) : (simple bool) 5th candle ago body must be higher than average. Optional argument, default is true.
     c3 (simple bool) : (simple bool) 4th candle ago body must be lower than average. Optional argument, default is true.
     c2 (simple bool) : (simple bool) 3rd candle ago body must be lower than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) 2nd candle ago body must be lower than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int) Length of average candle's body. Optional argument, default is 14.
  Returns: (bool)
 fallingWindow() 
  The "Falling Window" is a bearish pattern consists of two candles.
 gravestoneDoji(d0) 
  The "Gravestone Doji" is a bearish pattern consists of one candle.
  Parameters:
     d0 (simple float) : (simple float)  Current candle's body percentage out of candle range. Optional argument, default is 5.
 hammer(c0, n) 
  The "Hammer" is a bullish pattern consists of one candle.
  Parameters:
     c0 (simple bool) : (simple bool) Current candle's body must be lower than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 hangingMan(c0, n) 
  The "Hanging Man" is a bearish pattern consists of one candle.
  Parameters:
     c0 (simple bool) : (simple bool) Current candle's body must be lower than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 haramiCross(order, c1, n) 
  The "Harami Cross" candlestick pattern is a bullish/bearish pattern consists of two candles.
  Parameters:
     order (string) : (simple string) Pattern order type "bull" or "bear".
     c1 (simple bool) : (simple bool)   Previous candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)    Length of average candle's body. Optional argument, default is 14.
 harami(order, c1, c0, n) 
  The "Harami" candlestick pattern is a bullish/bearish pattern consists of two candles.
  Parameters:
     order (string) : (simple string) Pattern order type "bull" or "bear"
     c1 (simple bool) : (simple bool)   Previous candle's body must be higher than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool)   Current candle's body must be lower than average. Optional argument, default is true.
     n (simple int) : (simple int)    Length of average candle's body. Optional argument, default is 14.
 invertedHammer(c0, n) 
  The "Inverted Hammer" is a bullish pattern consists of one candle.
  Parameters:
     c0 (simple bool) : (simple bool)   Current candle's body must be lower than average. Optional argument, default is true.
     n (simple int) : (simple int)    Length of average candle's body. Optional argument, default is 14.
 kicking(order, c1, c0, n) 
  The "Kicking" candlestick pattern is a bullish/bearish pattern consists of two candles.
  Parameters:
     order (string) : (simple string) Pattern order type "bull" or "bear"
     c1 (simple bool) : (simple bool)   Previous candle's body must be higher than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool)   Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)    Length of average candle's body. Optional argument, default is 14.
 longLowerShadow(l0) 
  The "Long Lower Shadow" candlestick pattern is a bullish pattern consists of one candles.
  Parameters:
     l0 (simple float) : (simple float)  Current candle's lower wick min percentage out of candle range. Optional argument, default is 75.
 longUpperShadow(u0) 
  The "Long Upper Shadow" candlestick pattern is a bearish pattern consists of one candles.
  Parameters:
     u0 (simple float) : (simple float)  Current candle's upper wick min percentage out of candle range. Optional argument, default is 75.
 marubozuBlack(c0, n) 
  The "Marubozu Black" candlestick pattern is a bearish pattern consists of one candles.
  Parameters:
     c0 (simple bool) : (simple bool)   Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)    Length of average candle's body. Optional argument, default is 14.
 marubozuWhite(c0, n) 
  The "Marubozu White" candlestick pattern is a bullish pattern consists of one candles.
  Parameters:
     c0 (simple bool) : (simple bool)   Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)    Length of average candle's body. Optional argument, default is 14.
 morningDojiStar(c2, d1, c0, n) 
  The "Morning Doji Star" candlestick pattern is a bullish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool)  Before previous candle's body must be higher than average. Optional argument, default is true.
     d1 (simple float) : (simple float) Previous candle's body percentage out of candle range. Optional argument, default is 5.
     c0 (simple bool) : (simple bool)  Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)   Length of average candle's body. Optional argument, default is 14.
 morningStar(c2, c1, c0, n) 
  The "Morning Star" candlestick pattern is a bullish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Cuurent candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 onNeck(c1, c0, n) 
  The "On Neck" candlestick pattern is a bearish pattern consists of two candles.
  Parameters:
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Cuurent candle's body must be lower than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 piercing(c1, n) 
  The "Piercing" candlestick pattern is a bullish pattern consists of two candles.
  Parameters:
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 risingThreeMethods(c4, c3, c2, c1, c0, n) 
  The "Rising Three Methods" candlestick pattern is a bullish pattern consists of five candles.
  Parameters:
     c4 (simple bool) : (simple bool) 5th candle ago body must be higher than average. Optional argument, default is true.
     c3 (simple bool) : (simple bool) 4th candle ago body must be Lower than average. Optional argument, default is true.
     c2 (simple bool) : (simple bool) 3rd candle ago body must be Lower than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) 2nd candle ago body must be Lower than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 risingWindow() 
  The "Rising Window" candlestick pattern is a bullish pattern consists of two candle.
 shootingStar(c0, n) 
  The "Shooting Star" candlestick pattern is a bearish pattern consists of one candle.
  Parameters:
     c0 (simple bool) : (simple bool) Current candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 spinningTopBlack(l0, u0) 
  The "Spinning Top Black" is neither bullish or bearish.
  Parameters:
     l0 (simple float) : (simple float)  Current candle's lower wick min percentage out of candle range. Optional argument, default is 34.
     u0 (simple float) : (simple float)  Current candle's upper wick min percentage out of candle range. Optional argument, default is 34.
 spinningTopWhite(l0, u0) 
  The "Spinning Top White" is neither bullish or bearish.
  Parameters:
     l0 (simple float) : (simple float)  Current candle's lower wick min percentage out of candle range. Optional argument, default is 34.
     u0 (simple float) : (simple float)  Current candle's upper wick min percentage out of candle range. Optional argument, default is 34.
 threeBlackCrows(c2, c1, c0, n) 
  The "Three Black Crows" candlestick pattern is a bearish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Cuurent candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 threeWhiteSoldiers(c2, c1, c0, n) 
  The "Three White Soldiers" candlestick pattern is a bullish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool) Before previous candle's body must be higher than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     c0 (simple bool) : (simple bool) Cuurent candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 triStar(order, d2, d1, d0) 
  The "Tri Star" candlestick pattern is a bullish/bearish pattern consists of three candles.
  Parameters:
     order (simple string) : (simple string) Pattern order type "bull" or "bear".
     d2 (simple float) : (simple float)  Before previous candle's body percentage out of candle range. Optional argument, default is 5.
     d1 (simple float) : (simple float)  Previous candle's body percentage out of candle range. Optional argument, default is 5.
     d0 (simple float) : (simple float)  Current candle's body percentage out of candle range. Optional argument, default is 5.
 tweezerBottom(c1, n) 
  The "Tweezer Bottom" candlestick pattern is a bullish pattern consists of two candles.
  Parameters:
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 tweezerTop(c1, n) 
  The "Tweezer Top" candlestick pattern is a bearish pattern consists of two candles.
  Parameters:
     c1 (simple bool) : (simple bool) Previous candle's body must be higher than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
 upsideTasukiGap(c2, c1, n) 
  The "Tri Star" candlestick pattern is a bullish pattern consists of three candles.
  Parameters:
     c2 (simple bool) : (simple bool) Before Previous candle's body must be higher than average. Optional argument, default is true.
     c1 (simple bool) : (simple bool) Previous candle's body must be lower than average. Optional argument, default is true.
     n (simple int) : (simple int)  Length of average candle's body. Optional argument, default is 14.
DOW 30 - Market BreadthDOW 30 indicator is intended for short-term intraday analysis and should not be used solely alone. Best to use this indicator in a combination with technical and fundamental analysis. 
This indicator is calculated from all stocks in the DJI as of 8/9/2022;
- Evaluating VWAP, 
- 9 EMA,
- 20 EMA. 
Vwap Calculations;
Stock above Vwap = 1 (Vwap Bull),
Stock below Vwap = 1 (Vwap Bear),
As there are 30 stocks in the DJI, there is a max value of 30 Vwap Bulls/ Vwap Bears. 
Ema Calculation;
Stock above 9 EMA = 0.5 (EMA Bulls),
Stock below 9 EMA = 0.5 (EMA Bears),
Stock above 20 EMA = 0.5 (EMA Bulls),
Stock below 20 EMA = 0.5 (EMA Bears), 
For the EMA Bulls to reach 30 all stocks must be trading above both the 9 EMA and 20 EMA to reach a Max Value of 30. 
The reasoning for this calculation is to suggest the current strength and speed of the current turn in the market. 
Horizontal Lines:
There are three horizontal lines, MAX, MIN & Neutral; 
MAX & MIN
Resides at the 30 & 0 levels suggesting the market is currently at an extreme. Representing all stocks are moving in the same direction together.
When the MAX or MIN are represented in the VWAP Line this represents directional conviction in the underlining DJI.
Neutral
Neutral resides at the 15 level and represents that the market is either about to make a decision or is choppy. 
EXAMPLE
Below are some examples of how the DOW 30 indicator is able to represent the current market conditions. 
  
Understand Current Market Conditions, either being Bullish, Neutral, or Bearish. 
  
See live Market Mechanics, and understand the current market direction on a short-term timeframe.  
DOW 30 indicator is intended for short-term intraday analysis and should not be used solely alone. Best to use this indicator in a combination with technical and fundamental analysis. 
If there are any additional requests to the indicator feel free to leave a comment or privet message. 
Best of luck trading. 
 
Ichimoku [xdecow]The Ichimoku Kinko Hyo (Ichimoku Cloud) is a popular indicator / system.
In this version you will have a panel that shows the main signs of this system.
Each signal can have its status as bullish (weak, neutral or strong), consolidation and bearish (weak, neutral or strong).
 Signals 
 Kijun-Sen Cross 
Occurs when the price closes above/below the Kijun-sen.
 
 Weak Bullish: Occurs below the Kumo.
 Weak Bearish: Occurs above the Kumo.
 Bullish/Bearish Neutral: Occurs inside the Kumo.
 Strong Bullish: Occurs above the Kumo.
 Strong Bearish: Occurs below the Kumo.
 
 TK Cross 
Occurs when the Tenkan-sen crosses the Kijun-sen.
 
 Weak Bullish: Occurs when the crossing is below the Kumo.
 Weak Bearish: Occurs when the crossing is above the Kumo.
 Bullish/Bearish Neutral: Occurs when the crossing is inside the Kumo.
 Strong Bullish: Occurs when the crossing is above the Kumo.
 Strong Bearish: Occurs when the crossing is below the Kumo.
 
 Chikou Span Cross 
Occurs when the Chikou Span crosses the price.
 
 Weak Bullish: Occurs when current price is below the Kumo.
 Weak Bearish: Occurs when current price is above the Kumo.
 Bullish/Bearish Neutral: Occurs when current price is inside the Kumo.
 Strong Bullish: Occurs when current price is above the Kumo.
 Strong Bearish: Occurs when current price is below the Kumo.
 
 Kumo Breakout 
Occurs when the price closes above/below the Kumo.
 Kumo Twist 
Occurs when the Senkou Span A crosses the Senkou Span B ahead.
 
 Weak Bullish: Occurs when current price is below the Kumo.
 Weak Bearish: Occurs when current price is above the Kumo.
 Bullish/Bearish Neutral: Occurs when current price is inside the Kumo.
 Strong Bullish: Occurs when current price is above the Kumo.
 Strong Bearish: Occurs when current price is below the Kumo.
 
In addition, Senkou Span B turns golden when it is flat and the cloud is lighter when it is thin (default is half the average of the last 610).
Cyclic Smoothed RSI with Motive-Corrective Wave Indicator
This indicator uses the cyclic smoothed Relative Strength Index (cRSI) instead of the traditional Relative Strength Index (RSI). See below for more info on the benefits to the cRSI.
 My key contributions 
   1) A Weighted Moving Average (WMA) to track the general trend of the cRSI signal. This is very helpful in determining when the equity switches from bullish to bearish, which can be used to determine buy/sell points. This is then is used to color the region between the upper and lower cRSI bands (green above, red below).
   2) An attempt to detect the motive (impulse) and corrective and waves. Corrective waves are indicated A, B, C, D, E, F, G. F and G waves are not technically Elliot Waves, but the way I detect waves it is really hard to always get it right. Once and a while you could actually see G and F a second time. Motive waves are identified as s (strong) and w (weak). Strong waves have a peak above the cRSI upper band and weak waves have a peak below the upper band.
   3) My own divergence indicator for bull, hidden bull, bear, and hidden bear. I was not able to replicate the TradingView style of drawing a line from peak to peak, but for this indicator I think in the end it makes the chart cleaner.
There is a latency issue with an indicator that is based on moving averages. That means they tend to trigger right after key events. Perfect timing is not possible strictly with these indicators, but they do work very well "on average." However, my implementation has minimal latency as peaks (tops/bottoms) only require one bar to detect.
As a bit of an Easter Egg, this code can be tweaked and run as a strategy to get buy/sell signals. I use this code for both my indicator and for trading strategy. Just copy and past it into a new strategy script and just change it from study to a strategy, something like this:
strategy("cRSI + Waves Strategy with VWMA overlay", overlay=overlay)
The buy/sell code is at the end and just needs to be uncommented. I make no promises or guarantees about how good it is as a strategy, but it gives you some code and ideas to work with.
 Tuning 
1) Volume Weighted Moving Average (VWMA): This is a “hidden strategy” feature implemented that will display the high-low bands of the VWMA on the price chart if run the code using “overlay = true”.  
   -   If the equity does not have volume, then the VWMA will not show up. Uncheck this box and it will use the regular WMA (no volume).
   -   defines how far back the WMA averages price.
2) cRSI (Black line in the indicator)
   -   Increase to length that amount of time a band (upper/lower) stays high/low after a peak. Reduce the value to shorten the time. Just increment it up/down to see the effect.
   -   defines how far back the SMA averages the cRSI. This affects the purple line in the indicator.
   -   defines how many bars back the peak detector looks to determine if a peak has occurred. For example, a top is detected like this: current-bar down relative to the 1-bar-back, 1-bar-back up relative to 2-bars-back (look back = 1), c) 2-bars-back up relative to 3-bars-back (lookback = 2), and d) 3-bars-back up relative to 4-bars-back (lookback = 3). I hope that makes sense. There are only 2 options for this setting: 2 or 3 bars. 2 bars will be able to detect small peaks but create more “false” peaks that may not be meaningful. 3 bars will be more robust but can miss short duration peaks.
3) Waves
   - The check boxes are self explanatory for which labels they turn on and off on the plot.
4) Divergence Indicators
   - The check boxes are self explanatory for which labels they turn on and off on the plot.
 Hints 
  - The most common parameter to change is the  . Different stocks will have different levels of strength in their peaks. A setting of 2 may generate too many corrective waves.
  - Different times scales will give you different wave counts. This is to be expected. A counter impulse wave inside a corrective wave may actually go above the cRSI WMA on a smaller time frame. You may need to increase it one or two levels to see large waves.
  - Just because you see divergence (bear or hidden bear) does not mean a price is going to go down. Often price continues to rise through bears, so take note and that is normal. Bulls are usually pretty good indicators especially if you see them on C,E,G waves.
----------------------------------------------------------------------------------------------------------------------------
cyclic smoothed RSI (cRSI) indicator
----------------------------------------------------------------------------------------------------------------------------
The “core” code for the cyclic smoothed RSI (cRSI) indicator was written by Lars von Theinen and is subject to the terms of the Mozilla Public License 2.0 at mozilla.org Copyright (C) 2017 CC BY, whentotrade / Lars von Thienen. For more details on the cRSI Indicator: 
The cyclic smoothed RSI indicator is an enhancement of the classic RSI, adding
     1) additional smoothing according to the market vibration,
     2) adaptive upper and lower bands according to the cyclic memory and
     3) using the current dominant cycle length as input for the indicator.
It is much more responsive to market moves than the basic RSI. The indicator uses the dominant cycle as input to optimize signal, smoothing, and cyclic memory. To get more in-depth information on the cyclic-smoothed RSI indicator, please read Decoding The Hidden Market Rhythm - Part 1: Dynamic Cycles (2017), Chapter 4: "Fine-tuning technical indicators." You need to derive the dominant cycle as input parameter for the cycle length as described in chapter 4.
Hope this helps and good luck.
MTF VFSMA SqueezeThe purpose of this indicator is to detect a market squeeze (lack of volatility) period and to identify the initiation and direction of the breakout.
 It is based on Variety-Filtered, Squeeze Moving Averages   indicator.  
 The original indicator created by Loxx identifies both squeeze zones and breakouts/breakdowns. A squeeze zone is defined when price is below a specific volatility threshold calculated as the difference between a fast- and slow-moving average and filtered using ATR- or Pips-based threshold. 
 It operates on a single timeframe and  includes Loxx's Expanded Source Types, signals, alerts, etc. and 35+ Loxx's Moving Averages. These adaptive, minimal-lag indicators are built upon advanced mathematical and signal processing DSP techniques that far surpass traditional Moving Averages. 
  This currently published indicator includes the following main developments:  
 Squeeze Detection using Percentile Rank Method 
It detects the Squeeze by applying a Percentile Rank to the historical distance (spread) between the two MAs.
MA Spread: The basis for Squeeze detection is the distance between the two moving averages.
Percentile Rank: A statistical measure that indicates the percentage of past Spread values within the set lookback period that are lower than the current MA Spread.
Squeeze State: A Squeeze occurs when the Percentile Rank is below the set Squeeze Threshold (%)).
Example: If the threshold is 20% and the Rank is 15%, it means the MA Spread is in its tightest 15% range, below the set threshold. Therefore, the condition is currently met.
Goal: Objective volatility measurement that adapts to market conditions.
 Squeeze Duration Filter 
A key condition for a Breakout signal is that the MAs must have remained in the Squeeze zone for a specified minimum duration.
Goal: To filter out market noise and False Breakouts.
 Multi-Timeframe (MTF) Confluence 
Multi-Timeframe trend and squeeze monitoring for 3 timeframes (TFs).
Provides confirmation using the MA status from two higher timeframes (TF2, TF3).
Goal: Trend and momentum confirmation from a broader market context.
 Signals Only on Bar Close? 
By selecting the signalOnClose parameter to enabled, it is possible to avoid repainting on the chart TF. If it is checked, all events on the chart (L/S signals, Squeeze Start/End, MA color change) will only appear after the bar has closed, preventing repainting. Higher TF events remain in real-time.
Goal: To increase the reliability of signals.
 Multi-Level Alerts and Info Panel 
Comprehensive, confluence-weighted alerts and real-time status display.
Enhanced Alerts based on multi-timeframe confluences. Alerts are ready to enable/disable for Any alert() function call and ready for watchlists. Alert Frequency is also configurable in Inputs window. „Once per bar close” is the most reliable for signals. „Always” or „Once per bar” alert frequencies may generate temporary signal alerts.
Please note that even if "Once per bar close" is selected as alert frequency, this only applies to the chart TF, and TF2 and TF3 status may be modified until the close of the relevant candle.
Goal: Transparent decision-making.
  Other Improvements 
  Unlike the original indicator, the coloring of the MA curves on the chart depends on the relative positions of the fast MA and slow MA. The curves are colored bullish when the fast MA is above the slow MA, bearish when the opposite is true, and neutral in the squeeze zone.
 Data Window with Squeeze Start/End, Buy/Sell, Status, Squeeze Percentile etc. on all 3 TFs.
 Ready for Pine Screener.
Please be aware that currently only the chart TF is configurable in Pine Screener, TF2 and TF3 are set to their default values.
 Pine Script® version 6. 
 Limitations 
When setting the indicator parameters, please take into account the limitations of TradingView. (Lookback period of Percentile Rank and Moving Averages periods, Execution time limit (timeout) etc.)
For example, if a NaN% message appears as the Percentile Rank value, please reduce the lookback period.
 How to use it 
This indicator is a Breakout-following system, but it can also be the basis for Range Trading.
 
 The Setup Phase 
This is the preparation stage. The indicator signals low volatility as the bands tighten.
Squeeze Dynamics: Monitoring the Squeeze Duration is essential. The longer the price spends in the Squeeze zone, the more likely the resulting breakout will be powerful.
 The Signal Phase (Breakout)
The Breakout signal appears on the bar where the Percentile Rank first crosses above the Squeeze threshold, indicating a sudden return of volatility. 
Further condition: Meets the SqueezeDuration filter. 
Breakout direction: Bullish: Fast MA > SLow MA, Bearish: Fast MA < SLow MA
Applying MTF Confluence:
The most promising trades that are in line with higher timeframes:
Total Confluence: Chart TF Signal + TF2 Bullish/Bearish + TF3 Bullish/Bearish. This is the strongest, highest-probability setup.
Simple signal: Only the Chart TF signals. This should be handled with caution, as the higher timeframes (TF2, TF3) might still be in a Squeeze or in a conflicting state.
 Alternative Use: Range Trading within the Squeeze Bands
If the market has low volume, the squeeze bands can be used as dynamic support/resistance for bounces off the edges of the range:
The probability of a successful range trade increases if the boundaries of the squeeze zone have only been touched a few times previously. Each touch weakens the zone boundaries and increases the chance of a Breakout. 
 Suggested Tactics and Risk Management 
When using Breakout strategies, strict risk management and the use of confirmations are essential:
 Volume Confirmation: A strong, above-average volume Breakout candle increases the probability of a successful breakout.
 False Breakout: If the breakout occurs on low volume, there is a higher chance of a pullback and a False Breakout.
 Entry After Retest: A safer entry: wait until the price breaks out, but only enter if it returns to the squeeze zone and bounces back from there. This reduces the risk of a False Breakout trap.
The Risk of False Breakout:
 False Breakouts are part of any Breakout strategy. Always have a strict Stop Loss set.
 Reversal: Be prepared for the possibility that after a Breakout signal (e.g., Long), the price returns to the zone and then breaks out in the opposite (Short) direction.
  Please note that all technical analysis and trading signals only indicate probabilities. Always use your own risk management rules and follow market regulations. 
 Disclaimer 
This indicator is provided for educational and informational purposes only. It is not financial advice.
Trading involves substantial risk of loss and is not suitable for every investor. Past performance shown in examples is not indicative of future results.
The indicator provides signals and calculations, but trading decisions are solely your responsibility. Always:
Test strategies on paper before using real money
Never risk more than you can afford to lose
Understand that all trading involves risk
Consider seeking advice from a licensed financial advisor
The publisher makes no guarantees regarding accuracy, profitability, or performance. Use at your own risk.
v2.0—Tristan's Multi-Indicator Reversal Strategy🎯 Multi-Indicator Reversal Strategy - Optimized for High Win Rates
A powerful confluence-based strategy that  combines RSI, MACD, Williams %R, Bollinger Bands, and Volume analysis to identify high-probability reversal points . Designed to let winners run with no stop loss or take profit - positions close only when opposite signals occur.
Also, the 3 hour timeframe works VERY well—just a lot less trades.
 📈 Proven Performance 
This strategy has been backtested and optimized on multiple blue-chip stocks with 80-90%+ win rates on 1-hour timeframes from Aug 2025 through Oct 2025:
✅ V (Visa) - Payment processor
✅ MSFT (Microsoft) - Large-cap tech
✅ WMT (Walmart) - Retail leader
✅ IWM (Russell 2000 ETF) - Small-cap index
✅ NOW (ServiceNow) - Enterprise software
✅ WM (Waste Management) - Industrial services
These stocks tend to mean-revert at extremes, making them ideal candidates for this reversal-based approach. I only list these as a way to show you the performance of the script. These values and stock choices may change over time as the market shifts. Keep testing!
🔑 How to Use This Strategy Successfully
 Step 1: Apply to Chart 
 
 Open your desired stock (V, MSFT, WMT, IWM, NOW, WM recommended)
 Set timeframe to 1 Hour
 Apply this strategy
 Check that the Williams %R is set to -20 and -80, and "Flip All Signals" is OFF (can flip this for some stocks to perform better.)
 
 Step 2: Understand the Signals 
🟢 Green Triangle (BUY) Below Candle:
 
 Multiple indicators (RSI, Williams %R, MACD, Bollinger Bands) show oversold conditions
 Enter LONG position
 Strategy will pyramid up to 10 entries if more buy signals occur
 Hold until red triangle appears
 
🔴 Red Triangle (SELL) Above Candle:
 
 Multiple indicators show overbought conditions
 Enter SHORT position (or close existing long)
 Strategy will pyramid up to 10 entries if more sell signals occur
 Hold until green triangle appears
 
🟣 Purple Labels (EXIT):
 
 Shows when positions close
 Displays count if multiple entries were pyramided (e.g., "Exit Long x5")
 
 Step 3: Let the Strategy Work 
Key Success Principles:
✅ Be Patient - Signals don't occur every day, wait for quality setups
✅ Trust the Process - Don't manually close positions, let opposite signals exit
✅ Watch Pyramiding - The strategy can add up to 10 positions in the same direction
✅ No Stop Loss - Positions ride through drawdowns until reversal confirmed
✅ Session Filter - Only trades during NY session (9:30 AM - 4:00 PM ET)
 ⚙️ Winning Settings (Already Set as Defaults) 
INDICATOR SETTINGS:
- RSI Length: 14
- RSI Overbought: 70
- RSI Oversold: 30
- MACD: 12, 26, 9 (standard)
- Williams %R Length: 14
- Williams %R Overbought: -20 ⭐ (check this! And adjust to your liking)
- Williams %R Oversold: -80 ⭐ (check this! And adjust to your liking)
- Bollinger Bands: 20, 2.0
- Volume MA: 20 periods
- Volume Multiplier: 1.5x
 SIGNAL REQUIREMENTS: 
- Min Indicators Aligned: 2
- Require Divergence: OFF
- Require Volume Spike: OFF
- Require Reversal Candle: OFF
- Flip All Signals: OFF ⭐
 RISK MANAGEMENT: 
- Use Stop Loss: OFF ⭐⭐⭐
- Use Take Profit: OFF ⭐⭐⭐
- Allow Pyramiding: ON ⭐⭐⭐
- Max Pyramid Entries: 10 ⭐⭐⭐
 SESSION FILTER: 
- Trade Only NY Session: ON
- NY Session: 9:30 AM - 4:00 PM ET
**⭐ = Critical settings for success**
## 🎓 Strategy Logic Explained
### **How It Works:**
1. **Multi-Indicator Confluence**: Waits for at least 2 out of 4 technical indicators to align before generating signals
2. **Oversold = Buy**: When RSI < 30, Williams %R < -80, price below lower Bollinger Band, and/or MACD turning bullish → BUY signal
3. **Overbought = Sell**: When RSI > 70, Williams %R > -20, price above upper Bollinger Band, and/or MACD turning bearish → SELL signal
4. **Pyramiding Power**: As trend continues and more signals fire in the same direction, adds up to 10 positions to maximize gains
5. **Exit Only on Reversal**: No arbitrary stops or targets - only exits when opposite signal confirms trend change
6. **Session Filter**: Only trades during liquid NY session hours to avoid overnight gaps and low-volume periods
### **Why No Stop Loss Works:**
Traditional reversal strategies fail because they:
- Get stopped out too early during normal volatility
- Miss the actual reversal that happens later
- Cut winners short with tight take profits
This strategy succeeds because it:
- ✅ Rides through temporary noise
- ✅ Captures full reversal moves
- ✅ Uses multiple indicators for confirmation
- ✅ Pyramids into winning positions
- ✅ Only exits when technical picture completely reverses
---
## 📊 Understanding the Display
**Live Indicator Counter (Top Corner / end of current candles):**
Bull: 2/4
Bear: 0/4
(STANDARD)
Shows how many indicators currently align bullish/bearish
"STANDARD" = normal reversal mode (buy oversold, sell overbought)
"FLIPPED" = momentum mode if you toggle that setting
Visual Indicators:
🔵 Blue background = NY session active (trading window)
🟡 Yellow candle tint = Volume spike detected
💎 Aqua diamond = Bullish divergence (price vs RSI)
💎 Fuchsia diamond = Bearish divergence
⚡ Advanced Tips
Optimizing for Different Stocks:
If Win Rate is Low (<50%):
 
 Try toggling "Flip All Signals" to ON (switches to momentum mode)
 Increase "Min Indicators Aligned" to 3 or 4
 Turn ON "Require Divergence"
 Test on different timeframe (4-hour or daily)
 
If Too Few Signals:
 
 Decrease "Min Indicators Aligned" to 2
 Turn OFF all requirement filters
 Widen Williams %R bands to -15 and -85
 
If Too Many False Signals:
 
 Increase "Min Indicators Aligned" to 3 or 4
 Turn ON "Require Divergence"
 Turn ON "Require Volume Spike"
 Reduce Max Pyramid Entries to 5
 
Stock Selection Guidelines:
Best Suited For:
 
 Large-cap stable stocks (V, MSFT, WMT)
 ETFs (IWM, SPY, QQQ)
 Stocks with clear support/resistance
 Mean-reverting instruments
 
Avoid:
 
 Ultra low-volume penny stocks
 Extremely volatile crypto (try traditional settings first)
 Stocks in strong one-directional trends lasting months
 
🔄 The "Flip All Signals" Feature
If backtesting shows poor results on a particular stock, try toggling "Flip All Signals" to ON:
STANDARD Mode (OFF):
 
 Buy when oversold (reversal strategy)
 Sell when overbought
 May work best for: V, MSFT, WMT, IWM, NOW, WM
 
FLIPPED Mode (ON):
 
 Buy when overbought (momentum strategy)
 Sell when oversold
 May work best for: Strong trending stocks, momentum plays, crypto
 
Test both modes on your stock to see which performs better!
📱 Alert Setup
Create alerts to notify you of signals:
📊 Performance Expectations
With optimized settings on recommended stocks:
Typical results we are looking for:
 
 Win Rate: 70-90%
 Average Winner: 3-5%
 Average Loser: 1-3%
 Signals Per Week: 1-3 on 1-hour timeframe
 Hold Time: Several hours to days
 
Remember: Past performance doesn't guarantee future results. Always use proper risk management.
Tristan's Multi-Indicator Reversal StrategyMulti-Indicator Reversal Strategy - Buy Low, Sell High 
A comprehensive reversal detection system that  combines multiple proven technical indicators  to identify high-probability entry points for catching reversals at market extremes.
📊 Strategy Overview
This strategy is designed for traders who want to buy at lows and sell at highs by detecting when stocks are overextended and ready to reverse. It works by requiring multiple technical indicators to align before generating a signal, significantly reducing false entries.
 Best Used On: 
 
 Timeframe: 1-hour charts (also works on 15min, 30min, 4hour)
 Session: NY Trading Session (9:30 AM - 4:00 PM ET)
 Assets: Stocks, ETFs, Crypto (particularly volatile tech stocks like ZM, TSLA, AAPL)
 Trading Style: Swing trading, Intraday reversals
 
🔧 Technical Components
 The strategy combines FIVE powerful technical indicators: 
1. RSI (Relative Strength Index)
2. MACD (Moving Average Convergence Divergence)
3. Williams %R
4. Bollinger Bands
5. Volume Analysis
6. Divergence Detection (Optional)
🎨 Visual Signals
 Entry Signals: 
🟢 Green Triangle (below candle) = BUY LONG signal
🔴 Red Triangle (above candle) = SELL SHORT signal
 Exit Signals: 
🟣 Purple Label = Position closed (shows "x2", "x3" if multiple entries)
 Additional Indicators: 
💎 Aqua Diamond = Bullish divergence detected
💎 Fuchsia Diamond = Bearish divergence detected
🔵 Blue Background = NY Session active
🟡 Yellow Bar Tint = Volume spike detected
⚪ Small Circles = Near-signal conditions (2+ indicators aligned)
 Live Counter: 
 
 Top corner shows: "Bull: X/4" and "Bear: X/4"
 Indicates how many indicators currently align
 
⚙️ How to Use This Strategy
 For Beginners (More Signals): 
 
 Set "Min Indicators Aligned" to 2
 Turn OFF "Require Divergence"
 Turn OFF "Require Volume Spike"
 Turn OFF "Require Reversal Candle Pattern"
 Keep "Allow Multiple Entries" OFF
 
This gives you more frequent signals to learn from.
 For Advanced Traders (High Probability): 
 
 Set "Min Indicators Aligned" to 3 or 4
 Turn ON "Require Divergence"
 Turn ON "Require Volume Spike"
 Turn ON "Require Reversal Candle Pattern"
 Adjust stop loss to your risk tolerance
 
This filters for only the highest-quality setups.
 Recommended Settings for 1-Hour Charts: 
 
 Min Indicators Aligned: 3
 Stop Loss: 2.5%
 Take Profit: 5.0%
 RSI Length: 14
 Williams %R Length: 14
 Volume Multiplier: 1.5x
 Session: NY only (for stocks)
 
 BUY SIGNAL generated when:
2-4 indicators show oversold/bullish conditions: 
 
 RSI < 30 and turning up
 MACD crossing bullish or histogram positive
 Williams %R < -80 and turning up
 Price at/below lower Bollinger Band
 
Optional confirmations (if enabled):
 
 Bullish divergence detected
 Volume spike present
 Bullish reversal candle pattern
 
Session filter: Signals only during NY trading hours
 SELL SIGNAL Generated When:
2-4 indicators show overbought/bearish conditions: 
 
 RSI > 70 and turning down
 MACD crossing bearish or histogram negative
 Williams %R > -20 and turning down
 Price at/above upper Bollinger Band
 
Optional confirmations (if enabled):
 
 Bearish divergence detected
 Volume spike present
 Bearish reversal candle pattern
 
🛡️ Risk Management Features
 
 Automatic Stop Loss: Protects capital (default 2.5%)
 Take Profit Target: Locks in gains (default 5.0%)
 Pyramiding Control: Toggle to prevent position stacking
 Session Filter: Avoids overnight risk and low-liquidity periods
 Position Flipping: Automatically reverses when opposite signal appears
 
💡 Best Practices
✅ DO:
 
 Wait for candle close before entering (built into strategy)
 Use on volatile assets with clear trends
 Combine with your own analysis and risk management
 Backtest on your specific assets and timeframes
 Start with paper trading to learn the signals
 Adjust indicator requirements based on market conditions
 
❌ DON'T:
 
 Use on very low timeframes (<5 min) without adjustment
 Ignore the session filter on stocks
 Use maximum leverage - these are reversal trades
 Trade during major news events or earnings
 Expect 100% win rate - focus on risk/reward ratio
 
📊 Performance Notes
 This strategy prioritizes quality over quantity.  With default settings, you may see:
 
 2-5 signals per week on 1-hour charts
 Higher win rate with stricter settings (3-4 indicators aligned)
 Best performance during trending markets with clear reversals
 Reduced performance in choppy, sideways markets
 
Tip: Adjust "Min Indicators Aligned" based on market conditions:
 
 Trending markets: Use 3-4 (fewer but stronger signals)
 Range-bound markets: Use 2 (more signals, but watch for false breakouts)
OBV with Divergence (SMA Smoother)Title: OBV Divergence with SMA Smoothing
Description:
This indicator is a powerful tool designed to identify regular (reversal) and hidden (continuation) On-Balance Volume (OBV) divergences against price action. It uses a modified OBV calculation (an OBV Oscillator) and integrates pivot analysis to automatically highlight potential turning points or trend continuations directly on your chart.
Key Features
Advanced Divergence Detection: Automatically detects and labels four types of divergences:
Regular Bullish/Bearish: Signals potential trend reversals.
Regular Bullish: Price makes a Lower Low (LL) but the OBV Oscillator makes a Higher Low (HL).
Regular Bearish: Price makes a Higher High (HH) but the OBV Oscillator makes a Lower High (LH).
Hidden Bullish/Bearish: Signals potential trend continuations.
Hidden Bullish: Price makes a Higher Low (HL) but the OBV Oscillator makes a Lower Low (LL).
Hidden Bearish: Price makes a Lower High (LH) but the OBV Oscillator makes a Higher High (HH).
OBV Oscillator: Instead of plotting the raw OBV, this script uses the difference between the OBV and its Exponential Moving Average (EMA). This technique centers the indicator around zero, making it easier to visualize volume momentum shifts and clearly identify peaks and troughs for divergence analysis.
Optional SMA Smoothing Line (New Feature): An added Simple Moving Average (SMA) line can be toggled on to further smooth the OBV Oscillator. Traders can use this line for crossover signals or to confirm the underlying trend of the volume momentum, reducing whipsaws.
Customizable Lookback: The indicator allows you to define the lookback periods (Pivot Lookback Left/Right) for price and oscillator pivots, giving you precise control over sensitivity. The Max/Min of Lookback Range helps filter out divergences that are too close or too far apart.
ZS Master Vision Pro - Advanced Multi-Timeframe Trading SystemZS MASTER VISION PRO - PROFESSIONAL TRADING SUITE
Created by Zakaria Safri
A comprehensive, all-in-one trading system combining multiple proven technical analysis methods into a single, powerful indicator. Designed for traders who demand precision, clarity, and actionable signals across all timeframes.
KEY FEATURES
CORE TREND ALGORITHM
Adaptive ATR-based trend detection with dynamic support and resistance zones. Features Type A and Type B signal modes for different trading styles, strong signal detection in key reversal zones, and optional EMA source smoothing for noise reduction.
MULTI-LAYER EMA CLOUD SYSTEM
Five customizable EMA cloud layers for multi-timeframe analysis with theme-adaptive color coding across five professional themes. Optional line display for detailed MA tracking with configurable periods from scalping to position trading.
WAVE TREND OSCILLATOR
Advanced momentum oscillator with channel-based calculations featuring smart reversal detection at extreme overbought and oversold levels. Includes directional strength confirmation and customizable sensitivity with adjustable reaction periods.
DIVERGENCE SCANNER
Detects four types of divergence automatically:
- Regular Bullish: Price making lower lows while oscillator making higher lows
- Regular Bearish: Price making higher highs while oscillator making lower highs  
- Hidden Bullish: Trend continuation signals in uptrends
- Hidden Bearish: Trend continuation signals in downtrends
Automatic fractal-based detection with clear visual labels on chart.
MARKET BIAS INDICATOR
Heikin Ashi-based trend strength analysis with real-time bias calculation showing Bullish or Bearish combined with Strong or Weak conditions. Smoothed for cleaner signals and perfect for trend confirmation.
MOMENTUM SYSTEM
Proprietary momentum calculation using adaptive smoothing with growing and falling state detection. Normalized values for consistent interpretation and responsive to rapid market changes.
DYNAMIC SUPPORT AND RESISTANCE
Automatic pivot-based support and resistance level detection with adjustable left and right bar lookback. Non-repainting levels with visual clarity through color-coded lines.
LIVE INFORMATION DASHBOARD
Real-time market analysis panel displaying current trend direction, market bias based on Heikin Ashi, Wave Trend status and value, and momentum trend with state. Customizable display options with theme-adaptive colors.
VISUAL CUSTOMIZATION
FIVE PROFESSIONAL COLOR THEMES:
Pro - Modern green and red color scheme (default)
Classic - Traditional teal and red combination
Cyberpunk - Neon cyan and magenta contrast
Ocean - Blue and orange contrast
Sunset - Gold and red warmth
SIGNAL STYLES:
Labels with emoji indicators (BUY with rocket, SELL with bear, STRONG with lightning)
Arrows for clean minimal appearance
Triangles for classic approach
DISPLAY OPTIONS:
Color-coded candles following trend direction
Trend background highlighting for instant trend recognition
Optional EMA line display for detailed analysis
Adjustable transparency levels for personal preference
SMART ALERTS
Pre-configured alert conditions for all major signals:
Buy signals for standard entry opportunities
Sell signals for standard exit or short opportunities
Strong buy signals for high-confidence long entries
Strong sell signals for high-confidence short entries
Bullish divergence detection alerts
Bearish divergence detection alerts
Alert messages automatically include ticker symbol, current price, and specific signal type for quick decision making.
HOW TO USE
FOR TREND TRADERS:
Enable EMA Clouds with focus on Cloud 5 featuring 50 and 200 period moving averages. Wait for trend background color change to confirm direction. Enter on STRONG signals aligned with higher timeframe trend direction. Use support and resistance levels for strategic exits.
FOR SWING TRADERS:
Enable Wave Trend Oscillator information display. Look for oversold and overbought reversal setups. Confirm potential reversals with divergence scanner. Enter on smart reversal signals with proper risk management.
FOR SCALPERS:
Use Type B signal mode for more frequent trading signals. Enable Cloud 1 with 5 and 13 periods for quick trend confirmation. Focus on momentum growing and falling states for entry timing. Take quick entries on regular buy and sell signals.
FOR POSITION TRADERS:
Use Type A mode with higher ATR multiplier set to 3.0 or above. Enable only Cloud 5 with 50 and 200 periods for major trend confirmation. Only take STRONG signals for highest probability setups. Hold positions through minor pullbacks and noise.
RECOMMENDED SETTINGS
STOCKS ON DAILY TIMEFRAME:
Trend Period: 180
ATR Period: 155
ATR Multiplier: 2.1
Signal Mode: Type A
FOREX ON HOURLY AND 4-HOUR TIMEFRAMES:
Trend Period: 150
ATR Period: 120
ATR Multiplier: 2.5
Signal Mode: Type A
CRYPTOCURRENCY ON 15-MINUTE AND 1-HOUR TIMEFRAMES:
Trend Period: 100
ATR Period: 80
ATR Multiplier: 3.0
Signal Mode: Type B
SCALPING ON 1-MINUTE AND 5-MINUTE TIMEFRAMES:
Trend Period: 50
ATR Period: 40
ATR Multiplier: 2.0
Signal Mode: Type B
WHAT IS INCLUDED
Trend Analysis using ATR-based adaptive algorithm
Five EMA Cloud Layers for multi-timeframe confluence
Wave Trend Oscillator for momentum and reversal detection
Divergence Scanner detecting four types of divergence
Market Bias using Heikin Ashi-based trend strength
Momentum System with advanced momentum tracking
Support and Resistance Levels with automatic pivot detection
Live Dashboard showing real-time market analysis
Smart Alerts featuring six pre-configured alert types
Five Color Themes offering professional visual options
TECHNICAL DETAILS
CALCULATION METHODS:
Average True Range (ATR) for volatility adaptation
Exponential Moving Average (EMA) and Simple Moving Average (SMA) for trend smoothing
Wave Trend channel oscillator for momentum analysis
Fractal-based divergence detection algorithm
Heikin Ashi transformation for bias calculation
Logarithmic momentum calculation for precision
PERFORMANCE CHARACTERISTICS:
Optimized for maximum speed and efficiency
No repainting signals ensuring reliability
Works on all timeframes from 1 minute to monthly
Compatible with all instruments including stocks, forex, crypto, and futures
RISK DISCLAIMER
This indicator is a technical analysis tool and should not be used as the sole basis for trading decisions. Always use proper risk management and never risk more than you can afford to lose. Combine with other analysis methods and practice on demo accounts first. Past performance does not guarantee future results. Trading carries substantial risk and is not suitable for all investors.
SUPPORT AND UPDATES
Regular updates and continuous improvements
Based on proven technical analysis principles
Developed following Pine Coders best practices and standards
Clean, well-documented, and optimized code structure
WHY CHOOSE ZS MASTER VISION PRO
All-in-one solution eliminating the need for multiple indicators
Highly customizable to adapt to your specific trading style
Professional grade analysis with institutional-quality standards
Clean interface that is not cluttered or confusing
Works everywhere across all markets and all timeframes
Smart signals filtered for quality over quantity
Beautiful design featuring five professional color themes
Active development with regular improvements and updates
Transform your trading with ZS Master Vision Pro today.
Version 2.0 | Created by Zakaria Safri | Pine Script Version 5
ICT PDA - Gold & BTC (QuickScalp Bias/FVG/OB/OTE + Alerts)What this script does
This indicator implements a complete ICT Price Delivery Algorithm (PDA) workflow tailored for XAUUSD and BTCUSD. It combines HTF bias, OTE zones, Fair Value Gaps, Order Blocks, micro-BOS confirmation, and liquidity references into a single, cohesive tool with early and final alerts. The script is not a mashup for cosmetic plotting; each component feeds the next decision step.
Why this is original/useful
Symbol-aware impulse filter: A dynamic displacement threshold kTune adapts to Gold/BTC volatility (body/ATR vs. per-symbol factor), reducing noise on fast markets without hiding signals.
Scalping preset: “Quick Clean” mode limits drawings to the most recent bars and keeps only the latest FVG/OB zones for a clear chart.
Three display modes: Full, Clean, and Signals-Only to match analysis vs. execution.
Actionable alerts: Early heads-up when price enters OTE in the HTF bias direction, and Final alerts once mitigation + micro-break confirm the setup.
How it works (high-level logic)
HTF Bias: Uses request.security() on a user-selected timeframe (e.g., 240m) and EMA filter. Bias = close above/below HTF EMA.
Dealing Range & OTE: Recent swing high/low (pivot length configurable) define the range; OTE (62–79%) boxes are drawn contextually for up/down ranges.
Displacement: A candle’s body/ATR must exceed kTune and break short-term structure (displacement up/down).
FVG: 3-bar imbalance (bull: low > high ; bear: high < low ). Latest gaps are tracked and extended.
Order Blocks: Last opposite candle prior to a qualifying displacement that breaks recent highs/lows; zones are drawn and extended.
Entry & Alerts:
Long: Bullish bias + price inside buy-OTE + mitigation of a bullish FVG or OB + micro BOS up → “PDA Long (Final)”.
Short: Bearish bias + price inside sell-OTE + mitigation of a bearish FVG or OB + micro BOS down → “PDA Short (Final)”.
Early Alerts: Trigger as soon as price enters OTE in the direction of the active bias.
Inputs & controls (key ones)
Bias (HTF): timeframe minutes, EMA length.
Structure: ATR length, Impulse Threshold (Body/ATR), swing pivot length, OB look-back.
OTE/FVG/OB/LP toggles: show/hide components.
Auto-Tune: per-symbol factors for Gold/BTC + manual tweak.
Display/Performance: View Mode, keep-N latest FVG/OB, limit drawings to last N bars.
Recommended usage (scalping)
Timeframes: Execute on M1–M5 with HTF bias from 120–240m.
Defaults (starting point): ATR=14, Impulse Threshold≈1.6; Gold factor≈1.05, BTC factor≈0.90; Keep FVG/OB=2; last 200–300 bars; View Mode=Clean.
Workflow: Wait for OTE in bias direction → see mitigation (FVG/OB) → confirm with micro BOS → manage risk to nearest liquidity (prev-day H/L or recent swing).
Alerts available
“PDA Early Long/Short”
“PDA Long (Final)” / “PDA Short (Final)”
Attach alerts on “Any alert() function call” or the listed conditions.
Chart & screenshots
Please include symbol and timeframe on screenshots. The on-chart HUD shows the script name and state to help reviewers understand context.
Limitations / notes
This is a discretionary framework. Signals can cluster during news or extreme volatility; use your own risk management. No guarantee of profitability.
Changelog (brief)
v1.2 QuickScalp: added Quick Clean preset, safer array handling, symbol-aware impulse tuning, display modes.
------------------------------
ملخص عربي:
المؤشر يطبق تسلسل PDA عملي للذهب والبتكوين: تحيز من فريم أعلى، مناطق OTE، فجوات FVG، بلوكات أوامر OB، وتأكيد micro-BOS، مع تنبيهات مبكرة ونهائية. تمت إضافة وضع “Quick Clean” لتقليل العناصر على الشارت وحساسية إزاحة تتكيّف مع الأصل. للاستخدام كسكالب: نفّذ على M1–M5 مع تحيز 120–240 دقيقة، وابدأ من الإعدادات المقترحة بالأعلى. هذا إطار سلوكي وليس توصية مالية.
Dynamic Equity Allocation Model"Cash is Trash"? Not Always. Here's Why Science Beats Guesswork. 
Every retail trader knows the frustration: you draw support and resistance lines, you spot patterns, you follow market gurus on social media—and still, when the next bear market hits, your portfolio bleeds red. Meanwhile, institutional investors seem to navigate market turbulence with ease, preserving capital when markets crash and participating when they rally. What's their secret?
The answer isn't insider information or access to exotic derivatives. It's systematic, scientifically validated decision-making. While most retail traders rely on subjective chart analysis and emotional reactions, professional portfolio managers use quantitative models that remove emotion from the equation and process multiple streams of market information simultaneously.
This document presents exactly such a system—not a proprietary black box available only to hedge funds, but a fully transparent, academically grounded framework that any serious investor can understand and apply. The Dynamic Equity Allocation Model (DEAM) synthesizes decades of financial research from Nobel laureates and leading academics into a practical tool for tactical asset allocation.
Stop drawing colorful lines on your chart and start thinking like a quant. This isn't about predicting where the market goes next week—it's about systematically adjusting your risk exposure based on what the data actually tells you. When valuations scream danger, when volatility spikes, when credit markets freeze, when multiple warning signals align—that's when cash isn't trash. That's when cash saves your portfolio.
The irony of "cash is trash" rhetoric is that it ignores timing. Yes, being 100% cash for decades would be disastrous. But being 100% equities through every crisis is equally foolish. The sophisticated approach is dynamic: aggressive when conditions favor risk-taking, defensive when they don't. This model shows you how to make that decision systematically, not emotionally.
Whether you're managing your own retirement portfolio or seeking to understand how institutional allocation strategies work, this comprehensive analysis provides the theoretical foundation, mathematical implementation, and practical guidance to elevate your investment approach from amateur to professional.
 The choice is yours: keep hoping your chart patterns work out, or start using the same quantitative methods that professionals rely on. The tools are here. The research is cited. The methodology is explained. All you need to do is read, understand, and apply. 
The Dynamic Equity Allocation Model (DEAM) is a quantitative framework for systematic allocation between equities and cash, grounded in modern portfolio theory and empirical market research. The model integrates five scientifically validated dimensions of market analysis—market regime, risk metrics, valuation, sentiment, and macroeconomic conditions—to generate dynamic allocation recommendations ranging from 0% to 100% equity exposure. This work documents the theoretical foundations, mathematical implementation, and practical application of this multi-factor approach.
1. Introduction and Theoretical Background
1.1 The Limitations of Static Portfolio Allocation
Traditional portfolio theory, as formulated by Markowitz (1952) in his seminal work "Portfolio Selection," assumes an optimal static allocation where investors distribute their wealth across asset classes according to their risk aversion. This approach rests on the assumption that returns and risks remain constant over time. However, empirical research demonstrates that this assumption does not hold in reality. Fama and French (1989) showed that expected returns vary over time and correlate with macroeconomic variables such as the spread between long-term and short-term interest rates. Campbell and Shiller (1988) demonstrated that the price-earnings ratio possesses predictive power for future stock returns, providing a foundation for dynamic allocation strategies.
The academic literature on tactical asset allocation has evolved considerably over recent decades. Ilmanen (2011) argues in "Expected Returns" that investors can improve their risk-adjusted returns by considering valuation levels, business cycles, and market sentiment. The Dynamic Equity Allocation Model presented here builds on this research tradition and operationalizes these insights into a practically applicable allocation framework.
1.2 Multi-Factor Approaches in Asset Allocation
Modern financial research has shown that different factors capture distinct aspects of market dynamics and together provide a more robust picture of market conditions than individual indicators. Ross (1976) developed the Arbitrage Pricing Theory, a model that employs multiple factors to explain security returns. Following this multi-factor philosophy, DEAM integrates five complementary analytical dimensions, each tapping different information sources and collectively enabling comprehensive market understanding.
2. Data Foundation and Data Quality
2.1 Data Sources Used
The model draws its data exclusively from publicly available market data via the TradingView platform. This transparency and accessibility is a significant advantage over proprietary models that rely on non-public data. The data foundation encompasses several categories of market information, each capturing specific aspects of market dynamics.
First, price data for the S&P 500 Index is obtained through the SPDR S&P 500 ETF (ticker: SPY). The use of a highly liquid ETF instead of the index itself has practical reasons, as ETF data is available in real-time and reflects actual tradability. In addition to closing prices, high, low, and volume data are captured, which are required for calculating advanced volatility measures.
Fundamental corporate metrics are retrieved via TradingView's Financial Data API. These include earnings per share, price-to-earnings ratio, return on equity, debt-to-equity ratio, dividend yield, and share buyback yield. Cochrane (2011) emphasizes in "Presidential Address: Discount Rates" the central importance of valuation metrics for forecasting future returns, making these fundamental data a cornerstone of the model.
Volatility indicators are represented by the CBOE Volatility Index (VIX) and related metrics. The VIX, often referred to as the market's "fear gauge," measures the implied volatility of S&P 500 index options and serves as a proxy for market participants' risk perception. Whaley (2000) describes in "The Investor Fear Gauge" the construction and interpretation of the VIX and its use as a sentiment indicator.
Macroeconomic data includes yield curve information through US Treasury bonds of various maturities and credit risk premiums through the spread between high-yield bonds and risk-free government bonds. These variables capture the macroeconomic conditions and financing conditions relevant for equity valuation. Estrella and Hardouvelis (1991) showed that the shape of the yield curve has predictive power for future economic activity, justifying the inclusion of these data.
2.2 Handling Missing Data
A practical problem when working with financial data is dealing with missing or unavailable values. The model implements a fallback system where a plausible historical average value is stored for each fundamental metric. When current data is unavailable for a specific point in time, this fallback value is used. This approach ensures that the model remains functional even during temporary data outages and avoids systematic biases from missing data. The use of average values as fallback is conservative, as it generates neither overly optimistic nor pessimistic signals.
3. Component 1: Market Regime Detection
3.1 The Concept of Market Regimes
The idea that financial markets exist in different "regimes" or states that differ in their statistical properties has a long tradition in financial science. Hamilton (1989) developed regime-switching models that allow distinguishing between different market states with different return and volatility characteristics. The practical application of this theory consists of identifying the current market state and adjusting portfolio allocation accordingly.
DEAM classifies market regimes using a scoring system that considers three main dimensions: trend strength, volatility level, and drawdown depth. This multidimensional view is more robust than focusing on individual indicators, as it captures various facets of market dynamics. Classification occurs into six distinct regimes: Strong Bull, Bull Market, Neutral, Correction, Bear Market, and Crisis.
3.2 Trend Analysis Through Moving Averages
Moving averages are among the oldest and most widely used technical indicators and have also received attention in academic literature. Brock, Lakonishok, and LeBaron (1992) examined in "Simple Technical Trading Rules and the Stochastic Properties of Stock Returns" the profitability of trading rules based on moving averages and found evidence for their predictive power, although later studies questioned the robustness of these results when considering transaction costs.
The model calculates three moving averages with different time windows: a 20-day average (approximately one trading month), a 50-day average (approximately one quarter), and a 200-day average (approximately one trading year). The relationship of the current price to these averages and the relationship of the averages to each other provide information about trend strength and direction. When the price trades above all three averages and the short-term average is above the long-term, this indicates an established uptrend. The model assigns points based on these constellations, with longer-term trends weighted more heavily as they are considered more persistent.
3.3 Volatility Regimes
Volatility, understood as the standard deviation of returns, is a central concept of financial theory and serves as the primary risk measure. However, research has shown that volatility is not constant but changes over time and occurs in clusters—a phenomenon first documented by Mandelbrot (1963) and later formalized through ARCH and GARCH models (Engle, 1982; Bollerslev, 1986).
DEAM calculates volatility not only through the classic method of return standard deviation but also uses more advanced estimators such as the Parkinson estimator and the Garman-Klass estimator. These methods utilize intraday information (high and low prices) and are more efficient than simple close-to-close volatility estimators. The Parkinson estimator (Parkinson, 1980) uses the range between high and low of a trading day and is based on the recognition that this information reveals more about true volatility than just the closing price difference. The Garman-Klass estimator (Garman and Klass, 1980) extends this approach by additionally considering opening and closing prices.
The calculated volatility is annualized by multiplying it by the square root of 252 (the average number of trading days per year), enabling standardized comparability. The model compares current volatility with the VIX, the implied volatility from option prices. A low VIX (below 15) signals market comfort and increases the regime score, while a high VIX (above 35) indicates market stress and reduces the score. This interpretation follows the empirical observation that elevated volatility is typically associated with falling markets (Schwert, 1989).
3.4 Drawdown Analysis
A drawdown refers to the percentage decline from the highest point (peak) to the lowest point (trough) during a specific period. This metric is psychologically significant for investors as it represents the maximum loss experienced. Calmar (1991) developed the Calmar Ratio, which relates return to maximum drawdown, underscoring the practical relevance of this metric.
The model calculates current drawdown as the percentage distance from the highest price of the last 252 trading days (one year). A drawdown below 3% is considered negligible and maximally increases the regime score. As drawdown increases, the score decreases progressively, with drawdowns above 20% classified as severe and indicating a crisis or bear market regime. These thresholds are empirically motivated by historical market cycles, in which corrections typically encompassed 5-10% drawdowns, bear markets 20-30%, and crises over 30%.
3.5 Regime Classification
Final regime classification occurs through aggregation of scores from trend (40% weight), volatility (30%), and drawdown (30%). The higher weighting of trend reflects the empirical observation that trend-following strategies have historically delivered robust results (Moskowitz, Ooi, and Pedersen, 2012). A total score above 80 signals a strong bull market with established uptrend, low volatility, and minimal losses. At a score below 10, a crisis situation exists requiring defensive positioning. The six regime categories enable a differentiated allocation strategy that not only distinguishes binarily between bullish and bearish but allows gradual gradations.
4. Component 2: Risk-Based Allocation
4.1 Volatility Targeting as Risk Management Approach
The concept of volatility targeting is based on the idea that investors should maximize not returns but risk-adjusted returns. Sharpe (1966, 1994) defined with the Sharpe Ratio the fundamental concept of return per unit of risk, measured as volatility. Volatility targeting goes a step further and adjusts portfolio allocation to achieve constant target volatility. This means that in times of low market volatility, equity allocation is increased, and in times of high volatility, it is reduced.
Moreira and Muir (2017) showed in "Volatility-Managed Portfolios" that strategies that adjust their exposure based on volatility forecasts achieve higher Sharpe Ratios than passive buy-and-hold strategies. DEAM implements this principle by defining a target portfolio volatility (default 12% annualized) and adjusting equity allocation to achieve it. The mathematical foundation is simple: if market volatility is 20% and target volatility is 12%, equity allocation should be 60% (12/20 = 0.6), with the remaining 40% held in cash with zero volatility.
4.2 Market Volatility Calculation
Estimating current market volatility is central to the risk-based allocation approach. The model uses several volatility estimators in parallel and selects the higher value between traditional close-to-close volatility and the Parkinson estimator. This conservative choice ensures the model does not underestimate true volatility, which could lead to excessive risk exposure.
Traditional volatility calculation uses logarithmic returns, as these have mathematically advantageous properties (additive linkage over multiple periods). The logarithmic return is calculated as ln(P_t / P_{t-1}), where P_t is the price at time t. The standard deviation of these returns over a rolling 20-trading-day window is then multiplied by √252 to obtain annualized volatility. This annualization is based on the assumption of independently identically distributed returns, which is an idealization but widely accepted in practice.
The Parkinson estimator uses additional information from the trading range (High minus Low) of each day. The formula is: σ_P = (1/√(4ln2)) × √(1/n × Σln²(H_i/L_i)) × √252, where H_i and L_i are high and low prices. Under ideal conditions, this estimator is approximately five times more efficient than the close-to-close estimator (Parkinson, 1980), as it uses more information per observation.
4.3 Drawdown-Based Position Size Adjustment
In addition to volatility targeting, the model implements drawdown-based risk control. The logic is that deep market declines often signal further losses and therefore justify exposure reduction. This behavior corresponds with the concept of path-dependent risk tolerance: investors who have already suffered losses are typically less willing to take additional risk (Kahneman and Tversky, 1979).
The model defines a maximum portfolio drawdown as a target parameter (default 15%). Since portfolio volatility and portfolio drawdown are proportional to equity allocation (assuming cash has neither volatility nor drawdown), allocation-based control is possible. For example, if the market exhibits a 25% drawdown and target portfolio drawdown is 15%, equity allocation should be at most 60% (15/25).
4.4 Dynamic Risk Adjustment
An advanced feature of DEAM is dynamic adjustment of risk-based allocation through a feedback mechanism. The model continuously estimates what actual portfolio volatility and portfolio drawdown would result at the current allocation. If risk utilization (ratio of actual to target risk) exceeds 1.0, allocation is reduced by an adjustment factor that grows exponentially with overutilization. This implements a form of dynamic feedback that avoids overexposure.
Mathematically, a risk adjustment factor r_adjust is calculated: if risk utilization u > 1, then r_adjust = exp(-0.5 × (u - 1)). This exponential function ensures that moderate overutilization is gently corrected, while strong overutilization triggers drastic reductions. The factor 0.5 in the exponent was empirically calibrated to achieve a balanced ratio between sensitivity and stability.
5. Component 3: Valuation Analysis
5.1 Theoretical Foundations of Fundamental Valuation
DEAM's valuation component is based on the fundamental premise that the intrinsic value of a security is determined by its future cash flows and that deviations between market price and intrinsic value are eventually corrected. Graham and Dodd (1934) established in "Security Analysis" the basic principles of fundamental analysis that remain relevant today. Translated into modern portfolio context, this means that markets with high valuation metrics (high price-earnings ratios) should have lower expected returns than cheaply valued markets.
Campbell and Shiller (1988) developed the Cyclically Adjusted P/E Ratio (CAPE), which smooths earnings over a full business cycle. Their empirical analysis showed that this ratio has significant predictive power for 10-year returns. Asness, Moskowitz, and Pedersen (2013) demonstrated in "Value and Momentum Everywhere" that value effects exist not only in individual stocks but also in asset classes and markets.
5.2 Equity Risk Premium as Central Valuation Metric
The Equity Risk Premium (ERP) is defined as the expected excess return of stocks over risk-free government bonds. It is the theoretical heart of valuation analysis, as it represents the compensation investors demand for bearing equity risk. Damodaran (2012) discusses in "Equity Risk Premiums: Determinants, Estimation and Implications" various methods for ERP estimation.
DEAM calculates ERP not through a single method but combines four complementary approaches with different weights. This multi-method strategy increases estimation robustness and avoids dependence on single, potentially erroneous inputs.
The first method (35% weight) uses earnings yield, calculated as 1/P/E or directly from operating earnings data, and subtracts the 10-year Treasury yield. This method follows Fed Model logic (Yardeni, 2003), although this model has theoretical weaknesses as it does not consistently treat inflation (Asness, 2003).
The second method (30% weight) extends earnings yield by share buyback yield. Share buybacks are a form of capital return to shareholders and increase value per share. Boudoukh et al. (2007) showed in "The Total Shareholder Yield" that the sum of dividend yield and buyback yield is a better predictor of future returns than dividend yield alone.
The third method (20% weight) implements the Gordon Growth Model (Gordon, 1962), which models stock value as the sum of discounted future dividends. Under constant growth g assumption: Expected Return = Dividend Yield + g. The model estimates sustainable growth as g = ROE × (1 - Payout Ratio), where ROE is return on equity and payout ratio is the ratio of dividends to earnings. This formula follows from equity theory: unretained earnings are reinvested at ROE and generate additional earnings growth.
The fourth method (15% weight) combines total shareholder yield (Dividend + Buybacks) with implied growth derived from revenue growth. This method considers that companies with strong revenue growth should generate higher future earnings, even if current valuations do not yet fully reflect this.
The final ERP is the weighted average of these four methods. A high ERP (above 4%) signals attractive valuations and increases the valuation score to 95 out of 100 possible points. A negative ERP, where stocks have lower expected returns than bonds, results in a minimal score of 10.
5.3 Quality Adjustments to Valuation
Valuation metrics alone can be misleading if not interpreted in the context of company quality. A company with a low P/E may be cheap or fundamentally problematic. The model therefore implements quality adjustments based on growth, profitability, and capital structure.
Revenue growth above 10% annually adds 10 points to the valuation score, moderate growth above 5% adds 5 points. This adjustment reflects that growth has independent value (Modigliani and Miller, 1961, extended by later growth theory). Net margin above 15% signals pricing power and operational efficiency and increases the score by 5 points, while low margins below 8% indicate competitive pressure and subtract 5 points.
Return on equity (ROE) above 20% characterizes outstanding capital efficiency and increases the score by 5 points. Piotroski (2000) showed in "Value Investing: The Use of Historical Financial Statement Information" that fundamental quality signals such as high ROE can improve the performance of value strategies.
Capital structure is evaluated through the debt-to-equity ratio. A conservative ratio below 1.0 multiplies the valuation score by 1.2, while high leverage above 2.0 applies a multiplier of 0.8. This adjustment reflects that high debt constrains financial flexibility and can become problematic in crisis times (Korteweg, 2010).
6. Component 4: Sentiment Analysis
6.1 The Role of Sentiment in Financial Markets
Investor sentiment, defined as the collective psychological attitude of market participants, influences asset prices independently of fundamental data. Baker and Wurgler (2006, 2007) developed a sentiment index and showed that periods of high sentiment are followed by overvaluations that later correct. This insight justifies integrating a sentiment component into allocation decisions.
Sentiment is difficult to measure directly but can be proxied through market indicators. The VIX is the most widely used sentiment indicator, as it aggregates implied volatility from option prices. High VIX values reflect elevated uncertainty and risk aversion, while low values signal market comfort. Whaley (2009) refers to the VIX as the "Investor Fear Gauge" and documents its role as a contrarian indicator: extremely high values typically occur at market bottoms, while low values occur at tops.
6.2 VIX-Based Sentiment Assessment
DEAM uses statistical normalization of the VIX by calculating the Z-score: z = (VIX_current - VIX_average) / VIX_standard_deviation. The Z-score indicates how many standard deviations the current VIX is from the historical average. This approach is more robust than absolute thresholds, as it adapts to the average volatility level, which can vary over longer periods.
A Z-score below -1.5 (VIX is 1.5 standard deviations below average) signals exceptionally low risk perception and adds 40 points to the sentiment score. This may seem counterintuitive—shouldn't low fear be bullish? However, the logic follows the contrarian principle: when no one is afraid, everyone is already invested, and there is limited further upside potential (Zweig, 1973). Conversely, a Z-score above 1.5 (extreme fear) adds -40 points, reflecting market panic but simultaneously suggesting potential buying opportunities.
6.3 VIX Term Structure as Sentiment Signal
The VIX term structure provides additional sentiment information. Normally, the VIX trades in contango, meaning longer-term VIX futures have higher prices than short-term. This reflects that short-term volatility is currently known, while long-term volatility is more uncertain and carries a risk premium. The model compares the VIX with VIX9D (9-day volatility) and identifies backwardation (VIX > 1.05 × VIX9D) and steep backwardation (VIX > 1.15 × VIX9D).
Backwardation occurs when short-term implied volatility is higher than longer-term, which typically happens during market stress. Investors anticipate immediate turbulence but expect calming. Psychologically, this reflects acute fear. The model subtracts 15 points for backwardation and 30 for steep backwardation, as these constellations signal elevated risk. Simon and Wiggins (2001) analyzed the VIX futures curve and showed that backwardation is associated with market declines.
6.4 Safe-Haven Flows
During crisis times, investors flee from risky assets into safe havens: gold, US dollar, and Japanese yen. This "flight to quality" is a sentiment signal. The model calculates the performance of these assets relative to stocks over the last 20 trading days. When gold or the dollar strongly rise while stocks fall, this indicates elevated risk aversion.
The safe-haven component is calculated as the difference between safe-haven performance and stock performance. Positive values (safe havens outperform) subtract up to 20 points from the sentiment score, negative values (stocks outperform) add up to 10 points. The asymmetric treatment (larger deduction for risk-off than bonus for risk-on) reflects that risk-off movements are typically sharper and more informative than risk-on phases.
Baur and Lucey (2010) examined safe-haven properties of gold and showed that gold indeed exhibits negative correlation with stocks during extreme market movements, confirming its role as crisis protection.
7. Component 5: Macroeconomic Analysis
7.1 The Yield Curve as Economic Indicator
The yield curve, represented as yields of government bonds of various maturities, contains aggregated expectations about future interest rates, inflation, and economic growth. The slope of the yield curve has remarkable predictive power for recessions. Estrella and Mishkin (1998) showed that an inverted yield curve (short-term rates higher than long-term) predicts recessions with high reliability. This is because inverted curves reflect restrictive monetary policy: the central bank raises short-term rates to combat inflation, dampening economic activity.
DEAM calculates two spread measures: the 2-year-minus-10-year spread and the 3-month-minus-10-year spread. A steep, positive curve (spreads above 1.5% and 2% respectively) signals healthy growth expectations and generates the maximum yield curve score of 40 points. A flat curve (spreads near zero) reduces the score to 20 points. An inverted curve (negative spreads) is particularly alarming and results in only 10 points.
The choice of two different spreads increases analysis robustness. The 2-10 spread is most established in academic literature, while the 3M-10Y spread is often considered more sensitive, as the 3-month rate directly reflects current monetary policy (Ang, Piazzesi, and Wei, 2006).
7.2 Credit Conditions and Spreads
Credit spreads—the yield difference between risky corporate bonds and safe government bonds—reflect risk perception in the credit market. Gilchrist and Zakrajšek (2012) constructed an "Excess Bond Premium" that measures the component of credit spreads not explained by fundamentals and showed this is a predictor of future economic activity and stock returns.
The model approximates credit spread by comparing the yield of high-yield bond ETFs (HYG) with investment-grade bond ETFs (LQD). A narrow spread below 200 basis points signals healthy credit conditions and risk appetite, contributing 30 points to the macro score. Very wide spreads above 1000 basis points (as during the 2008 financial crisis) signal credit crunch and generate zero points.
Additionally, the model evaluates whether "flight to quality" is occurring, identified through strong performance of Treasury bonds (TLT) with simultaneous weakness in high-yield bonds. This constellation indicates elevated risk aversion and reduces the credit conditions score.
7.3 Financial Stability at Corporate Level
While the yield curve and credit spreads reflect macroeconomic conditions, financial stability evaluates the health of companies themselves. The model uses the aggregated debt-to-equity ratio and return on equity of the S&P 500 as proxies for corporate health.
A low leverage level below 0.5 combined with high ROE above 15% signals robust corporate balance sheets and generates 20 points. This combination is particularly valuable as it represents both defensive strength (low debt means crisis resistance) and offensive strength (high ROE means earnings power). High leverage above 1.5 generates only 5 points, as it implies vulnerability to interest rate increases and recessions.
Korteweg (2010) showed in "The Net Benefits to Leverage" that optimal debt maximizes firm value, but excessive debt increases distress costs. At the aggregated market level, high debt indicates fragilities that can become problematic during stress phases.
8. Component 6: Crisis Detection
8.1 The Need for Systematic Crisis Detection
Financial crises are rare but extremely impactful events that suspend normal statistical relationships. During normal market volatility, diversified portfolios and traditional risk management approaches function, but during systemic crises, seemingly independent assets suddenly correlate strongly, and losses exceed historical expectations (Longin and Solnik, 2001). This justifies a separate crisis detection mechanism that operates independently of regular allocation components.
Reinhart and Rogoff (2009) documented in "This Time Is Different: Eight Centuries of Financial Folly" recurring patterns in financial crises: extreme volatility, massive drawdowns, credit market dysfunction, and asset price collapse. DEAM operationalizes these patterns into quantifiable crisis indicators.
8.2 Multi-Signal Crisis Identification
The model uses a counter-based approach where various stress signals are identified and aggregated. This methodology is more robust than relying on a single indicator, as true crises typically occur simultaneously across multiple dimensions. A single signal may be a false alarm, but the simultaneous presence of multiple signals increases confidence.
The first indicator is a VIX above the crisis threshold (default 40), adding one point. A VIX above 60 (as in 2008 and March 2020) adds two additional points, as such extreme values are historically very rare. This tiered approach captures the intensity of volatility.
The second indicator is market drawdown. A drawdown above 15% adds one point, as corrections of this magnitude can be potential harbingers of larger crises. A drawdown above 25% adds another point, as historical bear markets typically encompass 25-40% drawdowns.
The third indicator is credit market spreads above 500 basis points, adding one point. Such wide spreads occur only during significant credit market disruptions, as in 2008 during the Lehman crisis.
The fourth indicator identifies simultaneous losses in stocks and bonds. Normally, Treasury bonds act as a hedge against equity risk (negative correlation), but when both fall simultaneously, this indicates systemic liquidity problems or inflation/stagflation fears. The model checks whether both SPY and TLT have fallen more than 10% and 5% respectively over 5 trading days, adding two points.
The fifth indicator is a volume spike combined with negative returns. Extreme trading volumes (above twice the 20-day average) with falling prices signal panic selling. This adds one point.
A crisis situation is diagnosed when at least 3 indicators trigger, a severe crisis at 5 or more indicators. These thresholds were calibrated through historical backtesting to identify true crises (2008, 2020) without generating excessive false alarms.
8.3 Crisis-Based Allocation Override
When a crisis is detected, the system overrides the normal allocation recommendation and caps equity allocation at maximum 25%. In a severe crisis, the cap is set at 10%. This drastic defensive posture follows the empirical observation that crises typically require time to develop and that early reduction can avoid substantial losses (Faber, 2007).
This override logic implements a "safety first" principle: in situations of existential danger to the portfolio, capital preservation becomes the top priority. Roy (1952) formalized this approach in "Safety First and the Holding of Assets," arguing that investors should primarily minimize ruin probability.
9. Integration and Final Allocation Calculation
9.1 Component Weighting
The final allocation recommendation emerges through weighted aggregation of the five components. The standard weighting is: Market Regime 35%, Risk Management 25%, Valuation 20%, Sentiment 15%, Macro 5%. These weights reflect both theoretical considerations and empirical backtesting results.
The highest weighting of market regime is based on evidence that trend-following and momentum strategies have delivered robust results across various asset classes and time periods (Moskowitz, Ooi, and Pedersen, 2012). Current market momentum is highly informative for the near future, although it provides no information about long-term expectations.
The substantial weighting of risk management (25%) follows from the central importance of risk control. Wealth preservation is the foundation of long-term wealth creation, and systematic risk management is demonstrably value-creating (Moreira and Muir, 2017).
The valuation component receives 20% weight, based on the long-term mean reversion of valuation metrics. While valuation has limited short-term predictive power (bull and bear markets can begin at any valuation), the long-term relationship between valuation and returns is robustly documented (Campbell and Shiller, 1988).
Sentiment (15%) and Macro (5%) receive lower weights, as these factors are subtler and harder to measure. Sentiment is valuable as a contrarian indicator at extremes but less informative in normal ranges. Macro variables such as the yield curve have strong predictive power for recessions, but the transmission from recessions to stock market performance is complex and temporally variable.
9.2 Model Type Adjustments
DEAM allows users to choose between four model types: Conservative, Balanced, Aggressive, and Adaptive. This choice modifies the final allocation through additive adjustments.
Conservative mode subtracts 10 percentage points from allocation, resulting in consistently more cautious positioning. This is suitable for risk-averse investors or those with limited investment horizons. Aggressive mode adds 10 percentage points, suitable for risk-tolerant investors with long horizons.
Adaptive mode implements procyclical adjustment based on short-term momentum: if the market has risen more than 5% in the last 20 days, 5 percentage points are added; if it has declined more than 5%, 5 points are subtracted. This logic follows the observation that short-term momentum persists (Jegadeesh and Titman, 1993), but the moderate size of adjustment avoids excessive timing bets.
Balanced mode makes no adjustment and uses raw model output. This neutral setting is suitable for investors who wish to trust model recommendations unchanged.
9.3 Smoothing and Stability
The allocation resulting from aggregation undergoes final smoothing through a simple moving average over 3 periods. This smoothing is crucial for model practicality, as it reduces frequent trading and thus transaction costs. Without smoothing, the model could fluctuate between adjacent allocations with every small input change.
The choice of 3 periods as smoothing window is a compromise between responsiveness and stability. Longer smoothing would excessively delay signals and impede response to true regime changes. Shorter or no smoothing would allow too much noise. Empirical tests showed that 3-period smoothing offers an optimal ratio between these goals.
10. Visualization and Interpretation
10.1 Main Output: Equity Allocation
DEAM's primary output is a time series from 0 to 100 representing the recommended percentage allocation to equities. This representation is intuitive: 100% means full investment in stocks (specifically: an S&P 500 ETF), 0% means complete cash position, and intermediate values correspond to mixed portfolios. A value of 60% means, for example: invest 60% of wealth in SPY, hold 40% in money market instruments or cash.
The time series is color-coded to enable quick visual interpretation. Green shades represent high allocations (above 80%, bullish), red shades low allocations (below 20%, bearish), and neutral colors middle allocations. The chart background is dynamically colored based on the signal, enhancing readability in different market phases.
10.2 Dashboard Metrics
A tabular dashboard presents key metrics compactly. This includes current allocation, cash allocation (complement), an aggregated signal (BULLISH/NEUTRAL/BEARISH), current market regime, VIX level, market drawdown, and crisis status.
Additionally, fundamental metrics are displayed: P/E Ratio, Equity Risk Premium, Return on Equity, Debt-to-Equity Ratio, and Total Shareholder Yield. This transparency allows users to understand model decisions and form their own assessments.
Component scores (Regime, Risk, Valuation, Sentiment, Macro) are also displayed, each normalized on a 0-100 scale. This shows which factors primarily drive the current recommendation. If, for example, the Risk score is very low (20) while other scores are moderate (50-60), this indicates that risk management considerations are pulling allocation down.
10.3 Component Breakdown (Optional)
Advanced users can display individual components as separate lines in the chart. This enables analysis of component dynamics: do all components move synchronously, or are there divergences? Divergences can be particularly informative. If, for example, the market regime is bullish (high score) but the valuation component is very negative, this signals an overbought market not fundamentally supported—a classic "bubble warning."
This feature is disabled by default to keep the chart clean but can be activated for deeper analysis.
10.4 Confidence Bands
The model optionally displays uncertainty bands around the main allocation line. These are calculated as ±1 standard deviation of allocation over a rolling 20-period window. Wide bands indicate high volatility of model recommendations, suggesting uncertain market conditions. Narrow bands indicate stable recommendations.
This visualization implements a concept of epistemic uncertainty—uncertainty about the model estimate itself, not just market volatility. In phases where various indicators send conflicting signals, the allocation recommendation becomes more volatile, manifesting in wider bands. Users can understand this as a warning to act more cautiously or consult alternative information sources.
11. Alert System
11.1 Allocation Alerts
DEAM implements an alert system that notifies users of significant events. Allocation alerts trigger when smoothed allocation crosses certain thresholds. An alert is generated when allocation reaches 80% (from below), signaling strong bullish conditions. Another alert triggers when allocation falls to 20%, indicating defensive positioning.
These thresholds are not arbitrary but correspond with boundaries between model regimes. An allocation of 80% roughly corresponds to a clear bull market regime, while 20% corresponds to a bear market regime. Alerts at these points are therefore informative about fundamental regime shifts.
11.2 Crisis Alerts
Separate alerts trigger upon detection of crisis and severe crisis. These alerts have highest priority as they signal large risks. A crisis alert should prompt investors to review their portfolio and potentially take defensive measures beyond the automatic model recommendation (e.g., hedging through put options, rebalancing to more defensive sectors).
11.3 Regime Change Alerts
An alert triggers upon change of market regime (e.g., from Neutral to Correction, or from Bull Market to Strong Bull). Regime changes are highly informative events that typically entail substantial allocation changes. These alerts enable investors to proactively respond to changes in market dynamics.
11.4 Risk Breach Alerts
A specialized alert triggers when actual portfolio risk utilization exceeds target parameters by 20%. This is a warning signal that the risk management system is reaching its limits, possibly because market volatility is rising faster than allocation can be reduced. In such situations, investors should consider manual interventions.
12. Practical Application and Limitations
12.1 Portfolio Implementation
DEAM generates a recommendation for allocation between equities (S&P 500) and cash. Implementation by an investor can take various forms. The most direct method is using an S&P 500 ETF (e.g., SPY, VOO) for equity allocation and a money market fund or savings account for cash allocation.
A rebalancing strategy is required to synchronize actual allocation with model recommendation. Two approaches are possible: (1) rule-based rebalancing at every 10% deviation between actual and target, or (2) time-based monthly rebalancing. Both have trade-offs between responsiveness and transaction costs. Empirical evidence (Jaconetti, Kinniry, and Zilbering, 2010) suggests rebalancing frequency has moderate impact on performance, and investors should optimize based on their transaction costs.
12.2 Adaptation to Individual Preferences
The model offers numerous adjustment parameters. Component weights can be modified if investors place more or less belief in certain factors. A fundamentally-oriented investor might increase valuation weight, while a technical trader might increase regime weight.
Risk target parameters (target volatility, max drawdown) should be adapted to individual risk tolerance. Younger investors with long investment horizons can choose higher target volatility (15-18%), while retirees may prefer lower volatility (8-10%). This adjustment systematically shifts average equity allocation.
Crisis thresholds can be adjusted based on preference for sensitivity versus specificity of crisis detection. Lower thresholds (e.g., VIX > 35 instead of 40) increase sensitivity (more crises are detected) but reduce specificity (more false alarms). Higher thresholds have the reverse effect.
12.3 Limitations and Disclaimers
DEAM is based on historical relationships between indicators and market performance. There is no guarantee these relationships will persist in the future. Structural changes in markets (e.g., through regulation, technology, or central bank policy) can break established patterns. This is the fundamental problem of induction in financial science (Taleb, 2007).
The model is optimized for US equities (S&P 500). Application to other markets (international stocks, bonds, commodities) would require recalibration. The indicators and thresholds are specific to the statistical properties of the US equity market.
The model cannot eliminate losses. Even with perfect crisis prediction, an investor following the model would lose money in bear markets—just less than a buy-and-hold investor. The goal is risk-adjusted performance improvement, not risk elimination.
Transaction costs are not modeled. In practice, spreads, commissions, and taxes reduce net returns. Frequent trading can cause substantial costs. Model smoothing helps minimize this, but users should consider their specific cost situation.
The model reacts to information; it does not anticipate it. During sudden shocks (e.g., 9/11, COVID-19 lockdowns), the model can only react after price movements, not before. This limitation is inherent to all reactive systems.
12.4 Relationship to Other Strategies
DEAM is a tactical asset allocation approach and should be viewed as a complement, not replacement, for strategic asset allocation. Brinson, Hood, and Beebower (1986) showed in their influential study "Determinants of Portfolio Performance" that strategic asset allocation (long-term policy allocation) explains the majority of portfolio performance, but this leaves room for tactical adjustments based on market timing.
The model can be combined with value and momentum strategies at the individual stock level. While DEAM controls overall market exposure, within-equity decisions can be optimized through stock-picking models. This separation between strategic (market exposure) and tactical (stock selection) levels follows classical portfolio theory.
The model does not replace diversification across asset classes. A complete portfolio should also include bonds, international stocks, real estate, and alternative investments. DEAM addresses only the US equity allocation decision within a broader portfolio.
13. Scientific Foundation and Evaluation
13.1 Theoretical Consistency
DEAM's components are based on established financial theory and empirical evidence. The market regime component follows from regime-switching models (Hamilton, 1989) and trend-following literature. The risk management component implements volatility targeting (Moreira and Muir, 2017) and modern portfolio theory (Markowitz, 1952). The valuation component is based on discounted cash flow theory and empirical value research (Campbell and Shiller, 1988; Fama and French, 1992). The sentiment component integrates behavioral finance (Baker and Wurgler, 2006). The macro component uses established business cycle indicators (Estrella and Mishkin, 1998).
This theoretical grounding distinguishes DEAM from purely data-mining-based approaches that identify patterns without causal theory. Theory-guided models have greater probability of functioning out-of-sample, as they are based on fundamental mechanisms, not random correlations (Lo and MacKinlay, 1990).
13.2 Empirical Validation
While this document does not present detailed backtest analysis, it should be noted that rigorous validation of a tactical asset allocation model should include several elements:
In-sample testing establishes whether the model functions at all in the data on which it was calibrated. Out-of-sample testing is crucial: the model should be tested in time periods not used for development. Walk-forward analysis, where the model is successively trained on rolling windows and tested in the next window, approximates real implementation.
Performance metrics should be risk-adjusted. Pure return consideration is misleading, as higher returns often only compensate for higher risk. Sharpe Ratio, Sortino Ratio, Calmar Ratio, and Maximum Drawdown are relevant metrics. Comparison with benchmarks (Buy-and-Hold S&P 500, 60/40 Stock/Bond portfolio) contextualizes performance.
Robustness checks test sensitivity to parameter variation. If the model only functions at specific parameter settings, this indicates overfitting. Robust models show consistent performance over a range of plausible parameters.
13.3 Comparison with Existing Literature
DEAM fits into the broader literature on tactical asset allocation. Faber (2007) presented a simple momentum-based timing system that goes long when the market is above its 10-month average, otherwise cash. This simple system avoided large drawdowns in bear markets. DEAM can be understood as a sophistication of this approach that integrates multiple information sources.
Ilmanen (2011) discusses various timing factors in "Expected Returns" and argues for multi-factor approaches. DEAM operationalizes this philosophy. Asness, Moskowitz, and Pedersen (2013) showed that value and momentum effects work across asset classes, justifying cross-asset application of regime and valuation signals.
Ang (2014) emphasizes in "Asset Management: A Systematic Approach to Factor Investing" the importance of systematic, rule-based approaches over discretionary decisions. DEAM is fully systematic and eliminates emotional biases that plague individual investors (overconfidence, hindsight bias, loss aversion).
References
Ang, A. (2014) *Asset Management: A Systematic Approach to Factor Investing*. Oxford: Oxford University Press.
Ang, A., Piazzesi, M. and Wei, M. (2006) 'What does the yield curve tell us about GDP growth?', *Journal of Econometrics*, 131(1-2), pp. 359-403.
Asness, C.S. (2003) 'Fight the Fed Model', *The Journal of Portfolio Management*, 30(1), pp. 11-24.
Asness, C.S., Moskowitz, T.J. and Pedersen, L.H. (2013) 'Value and Momentum Everywhere', *The Journal of Finance*, 68(3), pp. 929-985.
Baker, M. and Wurgler, J. (2006) 'Investor Sentiment and the Cross-Section of Stock Returns', *The Journal of Finance*, 61(4), pp. 1645-1680.
Baker, M. and Wurgler, J. (2007) 'Investor Sentiment in the Stock Market', *Journal of Economic Perspectives*, 21(2), pp. 129-152.
Baur, D.G. and Lucey, B.M. (2010) 'Is Gold a Hedge or a Safe Haven? An Analysis of Stocks, Bonds and Gold', *Financial Review*, 45(2), pp. 217-229.
Bollerslev, T. (1986) 'Generalized Autoregressive Conditional Heteroskedasticity', *Journal of Econometrics*, 31(3), pp. 307-327.
Boudoukh, J., Michaely, R., Richardson, M. and Roberts, M.R. (2007) 'On the Importance of Measuring Payout Yield: Implications for Empirical Asset Pricing', *The Journal of Finance*, 62(2), pp. 877-915.
Brinson, G.P., Hood, L.R. and Beebower, G.L. (1986) 'Determinants of Portfolio Performance', *Financial Analysts Journal*, 42(4), pp. 39-44.
Brock, W., Lakonishok, J. and LeBaron, B. (1992) 'Simple Technical Trading Rules and the Stochastic Properties of Stock Returns', *The Journal of Finance*, 47(5), pp. 1731-1764.
Calmar, T.W. (1991) 'The Calmar Ratio', *Futures*, October issue.
Campbell, J.Y. and Shiller, R.J. (1988) 'The Dividend-Price Ratio and Expectations of Future Dividends and Discount Factors', *Review of Financial Studies*, 1(3), pp. 195-228.
Cochrane, J.H. (2011) 'Presidential Address: Discount Rates', *The Journal of Finance*, 66(4), pp. 1047-1108.
Damodaran, A. (2012) *Equity Risk Premiums: Determinants, Estimation and Implications*. Working Paper, Stern School of Business.
Engle, R.F. (1982) 'Autoregressive Conditional Heteroskedasticity with Estimates of the Variance of United Kingdom Inflation', *Econometrica*, 50(4), pp. 987-1007.
Estrella, A. and Hardouvelis, G.A. (1991) 'The Term Structure as a Predictor of Real Economic Activity', *The Journal of Finance*, 46(2), pp. 555-576.
Estrella, A. and Mishkin, F.S. (1998) 'Predicting U.S. Recessions: Financial Variables as Leading Indicators', *Review of Economics and Statistics*, 80(1), pp. 45-61.
Faber, M.T. (2007) 'A Quantitative Approach to Tactical Asset Allocation', *The Journal of Wealth Management*, 9(4), pp. 69-79.
Fama, E.F. and French, K.R. (1989) 'Business Conditions and Expected Returns on Stocks and Bonds', *Journal of Financial Economics*, 25(1), pp. 23-49.
Fama, E.F. and French, K.R. (1992) 'The Cross-Section of Expected Stock Returns', *The Journal of Finance*, 47(2), pp. 427-465.
Garman, M.B. and Klass, M.J. (1980) 'On the Estimation of Security Price Volatilities from Historical Data', *Journal of Business*, 53(1), pp. 67-78.
Gilchrist, S. and Zakrajšek, E. (2012) 'Credit Spreads and Business Cycle Fluctuations', *American Economic Review*, 102(4), pp. 1692-1720.
Gordon, M.J. (1962) *The Investment, Financing, and Valuation of the Corporation*. Homewood: Irwin.
Graham, B. and Dodd, D.L. (1934) *Security Analysis*. New York: McGraw-Hill.
Hamilton, J.D. (1989) 'A New Approach to the Economic Analysis of Nonstationary Time Series and the Business Cycle', *Econometrica*, 57(2), pp. 357-384.
Ilmanen, A. (2011) *Expected Returns: An Investor's Guide to Harvesting Market Rewards*. Chichester: Wiley.
Jaconetti, C.M., Kinniry, F.M. and Zilbering, Y. (2010) 'Best Practices for Portfolio Rebalancing', *Vanguard Research Paper*.
Jegadeesh, N. and Titman, S. (1993) 'Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency', *The Journal of Finance*, 48(1), pp. 65-91.
Kahneman, D. and Tversky, A. (1979) 'Prospect Theory: An Analysis of Decision under Risk', *Econometrica*, 47(2), pp. 263-292.
Korteweg, A. (2010) 'The Net Benefits to Leverage', *The Journal of Finance*, 65(6), pp. 2137-2170.
Lo, A.W. and MacKinlay, A.C. (1990) 'Data-Snooping Biases in Tests of Financial Asset Pricing Models', *Review of Financial Studies*, 3(3), pp. 431-467.
Longin, F. and Solnik, B. (2001) 'Extreme Correlation of International Equity Markets', *The Journal of Finance*, 56(2), pp. 649-676.
Mandelbrot, B. (1963) 'The Variation of Certain Speculative Prices', *The Journal of Business*, 36(4), pp. 394-419.
Markowitz, H. (1952) 'Portfolio Selection', *The Journal of Finance*, 7(1), pp. 77-91.
Modigliani, F. and Miller, M.H. (1961) 'Dividend Policy, Growth, and the Valuation of Shares', *The Journal of Business*, 34(4), pp. 411-433.
Moreira, A. and Muir, T. (2017) 'Volatility-Managed Portfolios', *The Journal of Finance*, 72(4), pp. 1611-1644.
Moskowitz, T.J., Ooi, Y.H. and Pedersen, L.H. (2012) 'Time Series Momentum', *Journal of Financial Economics*, 104(2), pp. 228-250.
Parkinson, M. (1980) 'The Extreme Value Method for Estimating the Variance of the Rate of Return', *Journal of Business*, 53(1), pp. 61-65.
Piotroski, J.D. (2000) 'Value Investing: The Use of Historical Financial Statement Information to Separate Winners from Losers', *Journal of Accounting Research*, 38, pp. 1-41.
Reinhart, C.M. and Rogoff, K.S. (2009) *This Time Is Different: Eight Centuries of Financial Folly*. Princeton: Princeton University Press.
Ross, S.A. (1976) 'The Arbitrage Theory of Capital Asset Pricing', *Journal of Economic Theory*, 13(3), pp. 341-360.
Roy, A.D. (1952) 'Safety First and the Holding of Assets', *Econometrica*, 20(3), pp. 431-449.
Schwert, G.W. (1989) 'Why Does Stock Market Volatility Change Over Time?', *The Journal of Finance*, 44(5), pp. 1115-1153.
Sharpe, W.F. (1966) 'Mutual Fund Performance', *The Journal of Business*, 39(1), pp. 119-138.
Sharpe, W.F. (1994) 'The Sharpe Ratio', *The Journal of Portfolio Management*, 21(1), pp. 49-58.
Simon, D.P. and Wiggins, R.A. (2001) 'S&P Futures Returns and Contrary Sentiment Indicators', *Journal of Futures Markets*, 21(5), pp. 447-462.
Taleb, N.N. (2007) *The Black Swan: The Impact of the Highly Improbable*. New York: Random House.
Whaley, R.E. (2000) 'The Investor Fear Gauge', *The Journal of Portfolio Management*, 26(3), pp. 12-17.
Whaley, R.E. (2009) 'Understanding the VIX', *The Journal of Portfolio Management*, 35(3), pp. 98-105.
Yardeni, E. (2003) 'Stock Valuation Models', *Topical Study*, 51, Yardeni Research.
Zweig, M.E. (1973) 'An Investor Expectations Stock Price Predictive Model Using Closed-End Fund Premiums', *The Journal of Finance*, 28(1), pp. 67-78.
Extreme Pressure Zones Indicator (EPZ) [BullByte]Extreme Pressure Zones Indicator(EPZ) 
The Extreme Pressure Zones (EPZ) Indicator is a proprietary market analysis tool designed to highlight potential overbought and oversold "pressure zones" in any financial chart. It does this by combining several unique measurements of price action and volume into a single, bounded oscillator (0–100). Unlike simple momentum or volatility indicators, EPZ captures multiple facets of market pressure: price rejection, trend momentum, supply/demand imbalance, and institutional (smart money) flow. This is not a random mashup of generic indicators; each component was chosen and weighted to reveal extreme market conditions that often precede reversals or strong continuations.
 What it is? 
EPZ estimates buying/selling pressure and highlights potential extreme zones with a single, bounded 0–100 oscillator built from four normalized components. Context-aware weighting adapts to volatility, trendiness, and relative volume. Visual tools include adaptive thresholds, confirmed-on-close extremes, divergence, an MTF dashboard, and optional gradient candles.
 Purpose and originality (not a mashup) 
 Purpose:  Identify when pressure is building or reaching potential extremes while filtering noise across regimes and symbols.
 Originality:  EPZ integrates price rejection, momentum cascade, pressure distribution, and smart money flow into one bounded scale with context-aware weighting. It is not a cosmetic mashup of public indicators.
 Why a trader might use EPZ 
EPZ provides a multi-dimensional gauge of market extremes that standalone indicators may miss. Traders might use it to:
 Spot Reversals:  When EPZ enters an "Extreme High" zone (high red), it implies selling pressure might soon dominate. This can hint at a topside reversal or at least a pause in rallies. Conversely, "Extreme Low" (green) can highlight bottom-fish opportunities. The indicator's divergence module (optional) also finds hidden bullish/bearish divergences between price and EPZ, a clue that price momentum is weakening.
 Measure Momentum Shifts:  Because EPZ blends momentum and volume, it reacts faster than many single metrics. A rising MPO indicates building bullish pressure, while a falling MPO shows increasing bearish pressure. Traders can use this like a refined RSI: above 50 means bullish bias, below 50 means bearish bias, but with context provided by the thresholds.
 Filter Trades:  In trend-following systems, one could require EPZ to be in the bullish (green) zone before taking longs, or avoid new trades when EPZ is extreme. In mean-reversion systems, one might specifically look to fade extremes flagged by EPZ.
 Multi-Timeframe Confirmation:  The dashboard can fetch a higher timeframe EPZ value. For example, you might trade a 15-minute chart only when the 60-minute EPZ agrees on pressure direction.
 Components and how they're combined 
 Rejection (PRV)  – Captures price rejection based on candle wicks and volume (see Price Rejection Volume).
 Momentum Cascade (MCD)  – Blends multiple momentum periods (3,5,8,13) into a normalized momentum score.
 Pressure Distribution (PDI)  – Measures net buy/sell pressure by comparing volume on up vs down candles.
 Smart Money Flow (SMF)  – An adaptation of money flow index that emphasizes unusual volume spikes.
Each of these components produces a 0–100 value (higher means more bullish pressure). They are then weighted and averaged into the final Market Pressure Oscillator (MPO), which is smoothed and scaled. By combining these four views, EPZ stands out as a comprehensive pressure gauge – the whole is greater than the sum of parts
 Context-aware weighting: 
Higher volatility → more PRV weight
Trendiness up (RSI of ATR > 25) → more MCD weight
Relative volume > 1.2x → more PDI weight
SMF holds a stable weight
The weighted average is smoothed and scaled into MPO ∈   with 50 as the neutral midline.
 What makes EPZ stand out 
Four orthogonal inputs (price action, momentum, pressure, flow) unified in a single bounded oscillator with consistent thresholds.
Adaptive thresholds (optional) plus robust extreme detection that also triggers on crossovers, so static thresholds work reliably too.
Confirm Extremes on Bar Close (default ON): dots/arrows/labels/alerts print on closed bars to avoid repaint confusion.
Clean dashboard, divergence tools, pre-alerts, and optional on-price gradients. Visual 3D layering uses offsets for depth only,no lookahead.
 Recommended markets and timeframes 
 Best:  liquid symbols (index futures, large-cap equities, major FX, BTC/ETH).
 Timeframes:  5–15m (more signals; consider higher thresholds), 1H–4H (balanced), 1D (clear regimes).
 Use caution on illiquid or very low TFs where wick/volume geometry is erratic. 
 Logic and thresholds 
 MPO ∈  ; 50 = neutral. Above 50 = bullish pressure; below 50 = bearish. 
 Static thresholds (defaults):  thrHigh = 70, thrLow = 30; warning bands 5 pts inside extremes (65/35).
 Adaptive thresholds (optional): 
thrHigh = min(BaseHigh + 5, mean(MPO,100) + stdev(MPO,100) × ExtremeSensitivity)
thrLow = max(BaseLow − 5, mean(MPO,100) − stdev(MPO,100) × ExtremeSensitivity)
 Extreme detection 
High: MPO ≥ thrHigh with peak/slope or crossover filter.
Low: MPO ≤ thrLow with trough/slope or crossover filter.
 Cooldown:  5 bars (default). A new extreme will not print until the cooldown elapses, even if MPO re-enters the zone.
 Confirmation 
"Confirm Extremes on Bar Close" (default ON) gates extreme markers, pre-alerts, and alerts to closed bars (non-repainting).
 Divergences 
Pivot-based bullish/bearish divergence; tags appear only after left/right bars elapse (lookbackPivot).
 MTF 
HTF MPO retrieved with lookahead_off; values can update intrabar and finalize at HTF close. This is disclosed and expected.
 Inputs and defaults (key ones) 
 Core:  Sensitivity=1.0; Analysis Period=14; Smoothing=3; Adaptive Thresholds=OFF.
 Extremes:  Base High=70, Base Low=30; Extreme Sensitivity=1.5; Confirm Extremes on Bar Close=ON; Cooldown=5; Dot size Small/Tiny.
 Visuals:  Heatmap ON; 3D depth optional; Strength bars ON; Pre-alerts OFF; Divergences ON with tags ON; Gradient candles OFF; Glow ON.
 Dashboard:  ON; Position=Top Right; Size=Normal; MTF ON; HTF=60m; compact overlay table on price chart.
 Advanced caps:  Max Oscillator Labels=80; Max Extreme Guide Lines=80; Divergence objects=60.
 Dashboard: what each element means 
 Header:  EPZ ANALYSIS.
 Large readout:  Current MPO; color reflects state (extreme, approaching, or neutral).
 Status badge:  "Extreme High/Low", "Approaching High/Low", "Bullish/Neutral/Bearish".
 HTF cell (when MTF ON):  Higher-timeframe MPO, color-coded vs extremes; updates intrabar, settles at HTF close.
 Predicted (when MTF OFF):  Simple MPO extrapolation using momentum/acceleration—illustrative only.
 Thresholds:  Current thrHigh/thrLow (static or adaptive).
 Components:  ASCII bars + values for PRV, MCD, PDI, SMF.
 Market metrics:  Volume Ratio (x) and ATR% of price.
 Strength:  Bar indicator of |MPO − 50| × 2.
 Confidence:  Heuristic gauge (100 in extremes, 70 in warnings, 50 with divergence, else |MPO − 50|). Convenience only, not probability.
 How to read the oscillator 
 MPO Value (0–100):  A reading of 50 is neutral. Values above ~55 are increasingly bullish (green), while below ~45 are increasingly bearish (red). Think of these as "market pressure".
 Extreme Zones:  When MPO climbs into the bright orange/red area (above the base-high line, default 70), the chart will display a dot and downward arrow marking that extreme. Traders often treat this as a sign to tighten stops or look for shorts. Similarly, a bright green dot/up-arrow appears when MPO falls below the base-low (30), hinting at a bullish setup.
 Heatmap/Candles:  If "Pressure Heatmap" is enabled, the background of the oscillator pane will fade green or red depending on MPO. Users can optionally color the price candles by MPO value (gradient candles) to see these extremes on the main chart.
 Prediction Zone(optional):  A dashed projection line extends the MPO forward by a small number of bars (prediction_bars) using current MPO momentum and acceleration. This is a heuristic extrapolation best used for short horizons (1–5 bars) to anticipate whether MPO may touch a warning or extreme zone. It is provisional and becomes less reliable with longer projection lengths — always confirm predicted moves with bar-close MPO and HTF context before acting.
 Divergences:  When price makes a higher high but EPZ makes a lower high (bearish divergence), the indicator can draw dotted lines and a "Bear Div" tag. The opposite (lower low price, higher EPZ) gives "Bull Div". These signals confirm waning momentum at extremes.
 Zones:  Warning bands near extremes; Extreme zones beyond thresholds.
 Crossovers:  MPO rising through 35 suggests easing downside pressure; falling through 65 suggests waning upside pressure.
 Dots/arrows:  Extreme markers appear on closed bars when confirmation is ON and respect the 5-bar cooldown.
 Pre-alert dots (optional):  Proximity cues in warning zones; also gated to bar close when confirmation is ON.
 Histogram:  Distance from neutral (50); highlights strengthening or weakening pressure.
 Divergence tags:  "Bear Div" = higher price high with lower MPO high; "Bull Div" = lower price low with higher MPO low.
 Pressure Heatmap :  Layered gradient background that visually highlights pressure strength across the MPO scale; adjustable intensity and optional zone overlays (warning / extreme) for quick visual scanning.
 A typical reading:  If the oscillator is rising from neutral towards the high zone (green→orange→red), the chart may see strong buying culminating in a stall. If it then turns down from the extreme, that peak EPZ dot signals sell pressure.
 Alerts 
 EPZ: Extreme Context —  fires on confirmed extremes (respects cooldown).
 EPZ: Approaching Threshold —  fires in warning zones if no extreme.
 EPZ: Divergence —  fires on confirmed pivot divergences.
 Tip:  Set alerts to "Once per bar close" to align with confirmation and avoid intrabar repaint.
 Practical usage ideas 
 Trend continuation:  In positive regimes (MPO > 50 and rising), pullbacks holding above 50 often precede continuation; mirror for bearish regimes.
 Exhaustion caution:  E High/E Low can mark exhaustion risk; many wait for MPO rollover or divergence to time fades or partial exits.
 Adaptive thresholds:  Useful on assets with shifting volatility regimes to maintain meaningful "extreme" levels.
 MTF alignment:  Prefer setups that agree with the HTF MPO to reduce countertrend noise.
 Examples 
Screenshots captured in TradingView Replay to freeze the bar at close so values don't fluctuate intrabar. These examples use default settings and are reproducible on the same bars; they are for illustration, not cherry-picking or performance claims.
 Example 1 — BTCUSDT, 1h — E Low 
  
MPO closed at 26.6 (below the 30 extreme), printing a confirmed E Low. HTF MPO is 26.6, so higher-timeframe pressure remains bearish. Components are subdued (Momentum/Pressure/Smart$ ≈ 29–37), with Vol Ratio ≈ 1.19x and ATR% ≈ 0.37%. A prior Bear Div flagged weakening impulse into the drop. With cooldown set to 5 bars, new extremes are rate-limited. Many traders wait for MPO to curl up and reclaim 35 or for a fresh Bull Div before considering countertrend ideas; if MPO cannot reclaim 35 and HTF stays weak, treat bounces cautiously. Educational illustration only.
 Example 2 — ETHUSD, 30m — E High 
  
A strong impulse pushed MPO into the extreme zone (≥ 70), printing a confirmed E High on close. Shortly after, MPO cooled to ~61.5 while a Bear Div appeared, showing momentum lag as price pushed a higher high. Volume and volatility were elevated (≈ 1.79x / 1.25%). With a 5-bar cooldown, additional extremes won't print immediately. Some treat E High as exhaustion risk—either waiting for MPO rollover under 65/50 to fade, or for a pullback that holds above 50 to re-join the trend if higher-timeframe pressure remains constructive. Educational illustration only.
 Known limitations and caveats 
The MPO line itself can change intrabar; extreme markers/alerts do not repaint when "Confirm Extremes on Bar Close" is ON.
HTF values settle at the close of the HTF bar.
Illiquid symbols or very low TFs can be noisy; consider higher thresholds or longer smoothing.
Prediction line (when enabled) is a visual extrapolation only.
 For coders 
Pine v6. MTF via request.security with lookahead_off.
Extremes include crossover triggers so static thresholds also yield E High/E Low.
Extreme markers and pre-alerts are gated by barstate.isconfirmed when confirmation is ON.
Arrays prune oldest objects to respect resource limits; defaults (80/80/60) are conservative for low TFs.
3D layering uses negative offsets purely for drawing depth (no lookahead).
 Screenshot methodology: 
To make labels legible and to demonstrate non-repainting behavior, the examples were captured in TradingView Replay with "Confirm Extremes on Bar Close" enabled. Replay is used only to freeze the bar at close so plots don't change intrabar. The examples use default settings, include both Extreme Low and Extreme High cases, and can be reproduced by scrolling to the same bars outside Replay. This is an educational illustration, not a performance claim.
 Disclaimer 
This script is for educational purposes only and does not constitute financial advice. Markets involve risk; past behavior does not guarantee future results. You are responsible for your own testing, risk management, and decisions.
Market Sentiment Trend Gauge [LevelUp]Market Sentiment Trend Gauge simplifies technical analysis by mathematically combining momentum, trend direction, volatility position, and comparison against a market benchmark, into a single trend score from -100 to +100. Displayed in a separate pane below your chart, it resolves conflicting signals from RSI, moving averages, Bollinger Bands, and market correlations, providing clear insights into trend direction, strength, and relative performance.
 THE PROBLEM MARKET SENTIMENT TREND GAUGE (MSTG) SOLVES 
Traditional indicators often produce conflicting signals, such as RSI showing overbought while prices rise or moving averages indicating an uptrend despite market underperformance. MSTG creates a weighted composite score to answer: "What's the overall bias for this asset?"
 KEY COMPONENTS AND WEIGHTINGS 
 The trend score combines 
▪ Momentum (25%): Normalized 14-period RSI, capped at ±100.
▪ Trend Direction (35%): 10/21-period EMA relationships, 
▪ Volatility Position (20%): Price position, 20-period Bollinger Bands, capped at ±100.
▪ Market Comparison (20%): Daily performance vs. SPY benchmark, capped at ±100.
Final score = Weighted sum, smoothed with 5-period EMA.
 INTERPRETING THE MSTG CHART 
 Trend Score Ranges and Colors 
▪ Bright Green (>+30): Strong bullish; ideal for long entries.
▪ Light Green (+10 to +30): Weak bullish; cautiously favorable.
▪ Gray (-10 to +10): Neutral; avoid directional trades.
▪ Light Red (-10 to -30): Weak bearish; exercise caution.
▪ Bright Red (<-30): Strong bearish; high-risk for longs, consider shorts.
 Reference Lines 
▪ Zero Line (Gray): Separates bullish/bearish; crossovers signal trend changes.
▪ ±30 Lines (Dotted, Green/Red): Thresholds for strong trends.
▪ ±60 Lines (Dashed, Green/Red): Extreme strength zones (not overbought/oversold); manage risk (tighten stops, partial profits) but trends may persist.
 Background Colors 
▪ Green Tint (>+20): Bullish environment; favorable for longs.
▪ Red Tint (<-20): Bearish environment; caution for longs.
▪ Light Gray Tint (-20 to +20): Neutral/range-bound; wait for signals.
 Extreme Readings vs. Traditional Signals 
MSTG ±60 indicates maximum alignment of all factors, not reversals (unlike RSI >70/<30). Use for risk management, not automatic exits. Strong trends can sustain extremes; breakdowns occur below +30 or above -30.
 INFORMATION TABLE INTERPRETATION 
 Trend Score Symbols 
 ▲▲  >+30       strong bullish
 ▲  +10 to +30
 ●  -10 to +10  neutral
 ▼  -30 to -10
 ▼▼  <-30       strong bearish
  
 Colors: Green (positive), White (neutral), Red (negative).
 Momentum Score  
 +40 to +100  strong bullish
 0 to +40     moderate bullish
 -40 to 0     moderate bearish
 -100 to -40  strong bearish
 Market vs. Stock  
▪ Green: Stock outperforming market
▪ Red: Stock underperforming market
Example Interpretations:
 -0.45% / +1.23% (Green): Market down, stock up = Strong relative strength
 +2.10% / +1.50% (Red): Both rising, but stock lagging = Relative weakness
 -1.20% / -0.80% (Green): Both falling, but stock declining less = Defensive strength
 UNDERSTANDING EXTREME READINGS VS TRADITIONAL OVERBOUGHT/OVERSOLD 
⚠️ Critical distinctions
 Traditional Overbought/Oversold Signals: 
▪ Single indicator (like RSI >70 or <30) showing momentum excess
▪ Often suggests immediate reversal or pullback expected
▪ Based on "price moved too far, too fast" concept
 MSTG Extreme Readings (±60): 
▪ Composite alignment of 4 different factors (momentum, trend, volatility, relative strength)
▪ Indicates maximum strength in current direction
▪  NOT a reversal signal  - means "all systems extremely bullish/bearish"
 Key Differences: 
▪ RSI >70: "Price got ahead of itself, expect pullback"
▪ MSTG >+60: "Everything is extremely bullish right now"
▪ Strong trends can maintain extreme MSTG readings during major moves
▪ Breakdowns happen when MSTG falls below +30, not at +60
 Proper Usage of Extreme Readings: 
▪ Risk Management: Tighten stops, take partial profits
▪ Position Sizing: Reduce new position sizes at extremes  
▪ Trend Continuation: Watch for sustained extreme readings in strong markets
▪ Exit Signals: Look for breakdown below +30, not reversal from +60
 TRADING WITH MSTG 
 Quick Assessment 
1. Check trend symbol for direction.
2. Confirm momentum strength.
3. Note relative performance color.
Examples:
 ▲▲ 55.2 (Green), Momentum +28.4, Outperforming: Strong buy setup.
 ▼ -18.6 (Red), Momentum -43.2, Underperforming: Defensive positioning.
 Entry Conditions 
▪ Long: stock outperforming market
 - Score >+30 (bright green)
 - Sustained green background
 - ▲▲ symbol, 
▪ Short: stock underperforming market
 - Score <-30 (bright red)
 - Sustained red background
 - ▼▼ symbol
 Avoid Trading When: 
▪ Gray zone (-10 to +10).
▪ Rapid color changes or frequent zero-line crosses (choppy market).
▪ Gray background (range-bound).
 Risk Management: 
▪ Stop Loss: Exit on zero-line crossover against position.
▪ Take Profit: Partial at ±60 for risk control.
▪ Position Sizing: Larger when signals align; smaller in extremes or mixed conditions.
 KEY ADVANTAGES 
▪ Unified View: Weighted composite reduces noise and conflicts.
▪ Visual Clarity: 5-color system with gradients for rapid recognition.
▪ Market Context: Relative strength vs. SPY identifies leaders/laggards.
▪ Flexibility: Works across timeframes (1-min to weekly); customizable table.
▪ Noise Reduction: EMA smoothing minimizes false signals.
 EXAMPLES 
Strong Bull: Trend Score 71.9, Momentum Score 76.9
Neutral: Trend Score 0.1, Momentum Score -9.2
Strong Bear: Trend Score -51.7, Momentum Score -51.5
 PERFORMANCE AND LIMITATIONS 
Strengths: Trend identification, noise reduction, relative performance versus market.
Limitations: Lags at turning points, less effective in extreme volatility or non-trending markets.
Recommendations: View on multiple timeframes, combine with price action and fundamentals.






















