EMA 3-6-50 Crossover (Lenin77)The 3-6-50 EMA Crossover indicator is based on the use of three exponential moving averages (EMAs) of different lengths:
3-6-50 EMA: reflects the most recent price movements (very sensitive).
6-6-50 EMA: slightly smooths out short-term fluctuations.
50-50 EMA: represents the overall medium-term market trend.
The main objective of this indicator is to detect trend changes by the crossing of the shorter moving averages (3-6-50 EMA) above or below the 50-50 EMA.
⚙️ Working Logic
Bullish Cross:
Occurs when the shorter EMAs (3-6-50 EMA) cross the 50-50 EMA from below.
This crossover suggests that price momentum is shifting toward an uptrend, so it may be an opportunity to enter a buy position.
Sell Signal (Bearish Cross):
Generated when the short EMAs cross the 50 EMA from above.
It indicates that bearish momentum dominates the market and could be a good entry or exit point for short.
Visual Representation:
The chart shows the three EMAs in different colors for easy reading (green, orange, and blue).
At the crossover points, labels appear with the text BUY or SELL, indicating potential entry zones.
Optionally, the background can be colored to highlight the trend change and trigger automatic alerts.
Indicators and strategies
M2025Overview
We Provide you a custom made model called M2025
M2025 works based on some well-known fundamentals of trading, here are the filters/checks we used in this script:
MTF Support/Resistance (Based on RSI)
Liquidity Levels
Displacement/FVG
Support/Resistance (Based on RSI)
support and resistance are key concepts used to identify potential turning points in the market.
Support is a price level where demand is strong enough to prevent the price from falling further — it acts as a “floor.”
Resistance is a level where selling pressure tends to stop the price from rising — it acts as a “ceiling.”
Support and resistance help traders identify entry points, exit targets, and stop-loss areas, and are essential tools for understanding market structure and trend strength.
In M2025 , Support and Resistance are identified based on pivot high and pivot low found with RSI values.
Liquidity Levels
liquidity levels are price areas where a large number of buy or sell orders are clustered. These zones often form around swing highs, swing lows, support, and resistance levels, where many traders place stop-loss or pending orders.
Fair Value Gap
an FVG (Fair Value Gap) refers to an imbalance or “gap” in price action that occurs when the market moves too quickly in one direction, leaving little to no trading activity between certain price levels. This gap represents an area where buy and sell orders were not efficiently matched, creating an inefficiency in the market.
Traders often expect price to return to these zones later to “fill” the gap, restoring balance and are used to identify potential retracement zones.
How it works
This Model 2025 mainly works in 4 steps using all the techniques mentioned above.
Bullish Setup
Step 1 : Market is in Bullish Zone
Step 2 : Market Breaks the Buy Side Liquidity
Step 3 : Market Makes FVG while moving up before breaking the SSL
Step 4 : Market Breaks the Sell Side Liquidity within the Window Range
Bearish Setup
Step 1 : Market is in Bearish Zone
Step 2 : Market Breaks the Sell Side Liquidity
Step 3 : Market Makes FVG while moving down before breaking the BSL
Step 4 : Market Breaks the Buy Side Liquidity within the Window Range
Conclusion
M2025 works using well known trading techniques but the innovation in that is using them as steps and triggers which stimulate the real trading methods of many trades around the world. This is just an idea which we wanted to share with this great community of ours, thus this indicator is a tool for technical analysis and it should not be the sole basis for trading decisions for anyone out there. No indicator is perfect hence depending on one is not recommended.
Daily High/Low - Karan OberoiDaily High/Low - Karan Oberoi
This indicator automatically plots each day’s intraday high and low levels as horizontal lines on your chart — just like institutional traders mark daily ranges for precision trading.
- No rays or extensions – each line is drawn only across that day’s bars, keeping the chart clean and uncluttered.
- Auto-updates in real time – lines adjust dynamically as new highs or lows form throughout the trading day.
- Daily reset – when a new trading day begins, the previous day’s lines are locked in place and new ones start automatically.
- Customizable styling – choose colors, line styles (solid/dashed/dotted), and thickness to match your chart theme.
- Performance-safe – automatically deletes older lines beyond your chosen lookback period to avoid reaching TradingView’s line limit.
This is perfect for traders who rely on daily range analysis, liquidity sweeps, or intraday reversals — giving you clear, visual reference points of where price previously reached its extremes each session.
Follow for more ;)
SPX Prediction for ChaguanOnly for SPX 500, the closing. Based on ATR and day range.
It is for Chaguan's friends used only. Please check the guide created by the creator.
HTF Candles & ReversalsThis indicator, "HTF Candles & Reversals," provides multi-timeframe (HTF) candlestick overlays combined with advanced market structure and reversal detection, all on your main TradingView chart. It empowers traders to visualize the broader trend context, spot potential price reversals, and identify Fair Value Gaps (Imbalances) across up to eight user-selectable higher timeframes, supporting robust, efficient technical analysis.
Key Features
Multi-Timeframe Candle Display: Overlays up to eight higher timeframe candles (5m, 15m, 1H, 4H, 1D, 1W, 1M, 3M) on any chart. Each HTF candle features customizable body, border, and wick colors for bullish and bearish states.
Live Price Action Representation: HTF candle data is updated in real time, reflecting both completed and developing HTF candles for continuous context during current price moves.
Reversal Pattern Detection: Spots key bullish and bearish reversal patterns on both standard and HTF candles, marking them with green (bullish) and red (bearish) triangles beneath or above the main candles. HTF candles are optionally colored (lime/orange) upon identifying stronger reversal setups.
Fair Value Gap (Imbalance) Visualization: Automatically detects and highlights HTF imbalances (FVG) with transparent rectangles and mid-line overlays, indicating zones of potential price revisits and trading interest.
Day-of-Week Labels: For daily HTF candles, annotated with custom-positioned weekday labels (above/below), aiding in session structure recognition.
Customizable Visuals: Extensive settings for the distance, width, transparency, and buffer of overlaid candles, as well as label/timer position, alignment, sizing, and coloring—including per-element control for clarity and chart aesthetics.
HTF Timer & Labeling: Optionally display the HTF name and a remaining-time countdown for each candle, positioned at the top, bottom, or both, for improved situational awareness.
Performance Optimizations: Script is designed for overlay use with up to 500 candles, lines, and labels on charts with deep historical access (5,000 bars back).
How to Use
Apply the script to your chart and select the desired number of HTF candles to display.
Enable or disable triangles for reversal spotting and customize color schemes to match your workflow.
Leverage HTF overlays to validate lower timeframe signals, spot key levels, and monitor imbalances as price moves toward or away from high-interest zones.
Use settings to tune the look and adjust feature visibility for a clean, focused display.
Alerts
Built-in alert conditions are available for immediate notification when bullish or bearish reversal triangles appear—keeping you informed of critical setups in real time.
Use Case
Ideal for traders who want to:
Add higher-timeframe context and structure to their intraday or swing analysis
Quickly identify HTF-based support/resistance and potential reversal areas
Monitor market imbalances for order flow strategies or mean reversion plays
Access multi-timeframe price action cues without switching charts
Disclaimer: This indicator is intended for educational and analytical purposes. Always conduct your own analysis and manage risk appropriately when trading financial markets.
🎯 SLO Pro-J-Algo🎯 SLO Pro-J-Algo - Advanced Sessions, Liquidity & OTE Indicator
📊 Overview
SLO Pro-J-Algo is a comprehensive smart money trading indicator that combines three essential ICT (Inner Circle Trader) concepts into one powerful tool. Designed for professional traders who follow institutional trading methodologies, this indicator helps identify high-probability trade setups by tracking trading sessions, liquidity zones, and optimal trade entry points.
Perfect for: Forex, Gold (XAUUSD), Indices, and Crypto traders who use smart money concepts.
✨ Key Features
🕐 Trading Sessions
Asian, London, and New York sessions with customizable colors
Real-time session status indicators (🟢 Open / 🔴 Closed)
Session high/low tracking with visual lines
Session overlap detection (when multiple sessions are active)
Fully customizable transparency and colors for each session
Individual session background toggle - Show/hide each session independently
💧 Liquidity Sweeps
Automatic detection of Buyside Liquidity (BSL) and Sellside Liquidity (SSL)
Multiple sweep detection methods:
Wick Break - Any wick beyond the level
Close Break - Close price beyond the level
Full Retrace - Break and close back inside
Session labeling on liquidity zones (shows which session created the liquidity)
Adjustable sweep buffer (ATR-based) for precision
Visual customization (line style, width, colors, text size)
Smart zone management (displays only most relevant zones)
🎯 Optimal Trade Entry (OTE)
Automatic Fibonacci retracement zones (0.618, 0.705, 0.786)
Bullish OTE - Entry zones after swing lows with upside breakout
Bearish OTE - Entry zones after swing highs with downside breakout
Visual zone boxes highlighting the golden pocket (0.618-0.786)
Entry confirmation with ✅ / Exit tracking with ❌
Structure break requirement (optional)
Real-time status indicators (🎯↑ Bullish / 🎯↓ Bearish)
🎨 Customization Options
Master Controls
Enable/disable each component independently (Sessions, Liquidity, OTE)
Anti-Repainting Mode - Use confirmed signals with adjustable confirmation bars
Choose between live signals (instant but may repaint) or confirmed signals (stable, no repainting)
Session Colors
Individual ON/OFF toggles for each session background
Customizable colors for Asian, London, and New York sessions
Global transparency slider (0-100%)
Separate colors for session high/low lines
Liquidity Settings
Adjustable lookback period (5-30 bars)
Multiple sweep detection types
Custom colors for buyside and sellside liquidity
Line style options (Solid, Dashed, Dotted)
Control maximum displayed zones
OTE Settings
Adjustable swing length (5-50 bars)
Show/hide individual Fibonacci levels (0.618, 0.705, 0.786)
Optional structure break requirement
Custom colors for each Fibonacci level
Control maximum displayed OTE zones
📖 How to Use
For Day Traders:
Enable all three sessions to identify session boundaries
Watch for liquidity sweeps during session opens (especially London and New York)
Wait for price to retrace into OTE zones after liquidity is taken
Enter trades when price reaches 0.705-0.786 levels with confirmation
For Swing Traders:
Use higher timeframes (4H, Daily) for better swing detection
Focus on HTF liquidity sweeps that get taken during major sessions
Look for OTE zones that align with session highs/lows
Combine with market structure for confluence
Best Practices:
✅ Use Confirmed Signals mode to avoid repainting (set confirmation bars to 2-3)
✅ Combine with price action and market structure
✅ Wait for OTE entry confirmation (✅ indicator)
✅ Look for liquidity sweeps during high-impact session opens
✅ Use session overlaps for increased volatility awareness
⚠️ Always use proper risk management and stop losses
⚙️ Recommended Settings
For Forex/Gold (15m-1H charts):
- OTE Swing Length: 10-15
- Liquidity Lookback: 15
- Confirmation Bars: 2
- Require Structure Break: ON
- Session Transparency: 93%
```
### **For Indices (5m-15m charts):**
```
- OTE Swing Length: 8-10
- Liquidity Lookback: 12-15
- Confirmation Bars: 1-2
- Require Structure Break: ON
- Session Transparency: 90%
```
### **For Crypto (1H-4H charts):**
```
- OTE Swing Length: 12-20
- Liquidity Lookback: 15-20
- Confirmation Bars: 2-3
- Require Structure Break: OFF
- Session Transparency: 85%
🔔 Alert Features
Set up custom alerts for:
💧 Liquidity sweep events (BSL/SSL taken)
🕐 Session opens/closes (Asian, London, NY)
🎯 OTE zone entries (when price enters optimal entry zones)
📌 Important Notes
Anti-Repainting: Enable "Use Confirmed Signals" for stable, non-repainting indicators
Performance: Optimized for multiple timeframes with efficient memory management
Flexibility: All colors, sizes, and thresholds are fully customizable
Education: Best used by traders familiar with ICT concepts and smart money trading
⚠️ Disclaimer
This indicator is a technical analysis tool and should not be used as the sole basis for trading decisions. Always:
Conduct your own research and analysis
Use proper risk management (stop losses, position sizing)
Practice on demo accounts before live trading
Understand that past performance does not guarantee future results
Consider multiple timeframe analysis and market context
Trading involves substantial risk of loss. Trade responsibly.
📞 Support & Feedback
If you find this indicator helpful, please:
⭐ Leave a rating and review
💬 Share your feedback and suggestions
🔔 Follow for updates and new indicators
Happy Trading! 🎯📈
Historical Vertical Lines 17:00-20:30Historical Vertical Lines 17:00-20:30. These lines show this specific time. You can edit the times via pine script. Easy.
Institutional Signal Engine (ISE) 🧭 Overview
ISE is a multi-layer institutional trading system that combines trend, volatility, volume, and multi-timeframe logic into one advanced framework.
It identifies high-probability reversals, institutional accumulation/distribution phases, and Smart Buy/Sell setups confirmed by higher-timeframe filters.
The indicator integrates:
TSI–RSI–ATR dashboard (weekly basis)
Monthly trend filter (long-term direction)
A/D Line divergences and volume spikes on compression
Dynamic Sigma ±1…±4 volume bands (VWMA-based)
Smart visual signals, alerts, and real-time data tables
⚙️ Core Logic – Step by Step
1️⃣ Multi-Timeframe Engine
Calculates TSI, RSI, and ATR on the weekly timeframe to filter out short-term noise.
Uses a 10-period SMA on monthly close as long-term filter:
Above = monthly bullish bias
Below = monthly bearish bias
2️⃣ Weekly Trend Change Detection
A 10-bar SMA defines the weekly trend:
Green arrow “▲” = Bullish reversal
Red arrow “▼” = Bearish reversal
Automatic alerts are triggered when a reversal occurs.
3️⃣ Directional Score (0–100%)
A 4-factor composite score measures directional strength:
Component Weight Effect
TSI trend direction 25% Momentum bias
RSI above/below 50 25% Market strength
ATR above volatility threshold 25% Volatility confirmation
Monthly trend alignment 25% Institutional filter
Score ≥ 75% = strong institutional confirmation
Combined with monthly bias, this defines Smart Entry Zones
4️⃣ Institutional Module
🔸 A/D Line Divergences
Detects when volume flow diverges from price:
Price down + A/D up → bullish divergence (accumulation)
Price up + A/D down → bearish divergence (distribution)
🔸 Volume Spikes on Compression
Flags breakouts when price range contracts but volume surges sharply.
Indicates institutional activity and momentum expansion.
🔸 Smart Buy / Smart Sell Conditions
Smart signals appear only when all conditions align:
Divergence or volume spike,
Score ≥ 75%,
Monthly trend confirmation,
(Optional) Weekly trend reversal if enabled.
✅ Smart Buy (C) → Green triangle below bar
✅ Smart Sell (V) → Red triangle above bar
5️⃣ Advanced Visual Signals
Symbol Meaning Interpretation
▲ / ▼ Weekly trend reversal Direction change
🟢 C / 🔴 V Smart Buy / Smart Sell Institutional setup
🔵 / 🟠 Circles Ideal confirmed trades Retrospective validation
💠 Fuchsia Diamond Probable low Anticipated bullish reversal
↟ / ↡ RSI/SMA extreme cross Visual early warning
6️⃣ Sigma ±1..±4 Volume Bands (VWMA-70)
Based on Volume Weighted Moving Average (VWMA 70), not Bollinger.
Defines 4 upper and 4 lower Sigma levels relative to the current equilibrium (POC).
Acts as a probabilistic map of volume balance zones.
Labels display real-time price values for each band (auto-updated each bar).
7️⃣ Real-Time Information Tables
📋 Oscillator Table (Right side)
Displays the status of three oscillators:
Indicator Signal
Stochastic BUY / SELL / NEUTRAL
Fisher Transform BUY / SELL / NEUTRAL
Williams %R BUY / SELL / NEUTRAL
Colors: 🟢 = Buy, 🔴 = Sell, 🟠 = Neutral
📊 Volume Table (Top right)
Shows:
Volume Direction: buying / selling / neutral
Trend vs previous bar: increasing / decreasing / stable
Current vs previous volume values
🧠 How to Use and Interpret
🔹 Step 1 – Identify Context
Use the monthly filter and weekly arrows to determine the institutional direction.
📈 Both up = bullish environment
📉 Both down = bearish environment
Mixed = neutral / uncertain
🔹 Step 2 – Wait for Alignment
Trade only when Smart Signals appear in the same direction as the higher timeframe trend.
Green “C” = buy signal within bullish structure
Red “V” = sell signal within bearish structure
🔹 Step 3 – Confirm with Volumes and Sigma Bands
If price is near Sigma −2 / −3, expect potential rebound (buy zones).
If price is near Sigma +2 / +3, expect exhaustion (sell zones).
Strong volume spike + Smart signal = institutional confirmation
🔹 Step 4 – Manage Trades
Use weekly ATR or Sigma ±2 as volatility-based stop levels.
Exit on opposite Smart signal or trend reversal arrow.
📈 Interpretation Summary
Condition Meaning Bias
Green ▲ + Smart Buy + Score ≥75 Confirmed bullish reversal Long setup
Red ▼ + Smart Sell + Score ≥75 Confirmed bearish reversal Short setup
Fuchsia Diamond ⚡ Probable local bottom Early long opportunity
Narrow Sigma bands Compression → Pre-breakout Wait for expansion
Wide Sigma bands High volatility / exhaustion Avoid new entries
⚡ Summary
Aspect Description
Name Lanfranco Bilotti – Institutional Trading + Alert
Structure Multi-timeframe, multi-indicator system
Core Modules TSI, RSI, ATR, A/D Divergence, Volume Spike, Sigma Bands
Signals Smart Buy/Sell, Probable Low, Trend Arrows
Alerts Automatic weekly reversal alerts
Filters Weekly and monthly trend filters
Output Visual dashboard + dual data tables
Best timeframe Weekly or Daily (for institutional flow)
Main goal Detect institutional trend phases and confirm high-probability entries
💼 Trading Instructions (Usage Guide) !!!!
🔹 Step-by-Step Usage
1️⃣ Choose timeframe
Recommended use on Daily or Weekly charts.
Institutional alignment works best when Weekly = Monthly trend.
2️⃣ Identify market context
📈 Bullish environment: Monthly filter = UP and weekly arrow ▲
📉 Bearish environment: Monthly filter = DOWN and weekly arrow ▼
3️⃣ Wait for confirmation
Smart BUY (C) → appears only when volume, trend, and oscillators align.
Smart SELL (V) → confirmed institutional distribution setup.
4️⃣ Entry rules (example)
Long entry: when Smart BUY (C) appears and the current price is near Sigma −1 or −2.
Short entry: when Smart SELL (V) appears and the price is near Sigma +1 or +2.
5️⃣ Stop loss suggestion (statistical)
Use weekly ATR or next Sigma band as volatility-based stop.
Example: if entry at Sigma −1 → stop below Sigma −2.
6️⃣ Exit strategy
Exit when the opposite Smart Signal appears (C → V or V → C).
Or when a new weekly reversal arrow ▲ / ▼ is printed.
🔹 Interpretation Summary
Symbol Meaning Action Bias
▲ / ▼ Weekly trend reversal Confirms long / short bias
🟢 C Smart Buy Long entry zone
🔴 V Smart Sell Short entry zone
💠 Fuchsia Diamond Probable low Early long opportunity
↟ / ↡ RSI/SMA extreme Momentum exhaustion zone
=================================================
Trade only in the direction of the higher timeframe trend.
Smart BUY (C) → enter long when price is near Sigma −1 / −2 and monthly trend = UP.
Smart SELL (V) → enter short when price is near Sigma +1 / +2 and monthly trend = DOWN.
Exit on the opposite Smart signal or when a new weekly arrow ▲ / ▼ appears.
Use the weekly ATR or next Sigma band for stop-loss placement.
Always confirm signals at candle close.
Trend Direction (ZigZag)This indicator is designed to visually identify and label key market structure points—Higher Highs (HH), Higher Lows (HL), Lower Highs (LH), and Lower Lows (LL)—using a ZigZag algorithm that efficiently tracks trend reversals and swing pivots. It overlays dynamic lines, labels, and color-coded bars directly onto your TradingView chart, making it ideal for traders seeking a clearer view of price structure for strategy development and confirmation.
What the Indicator Does
Automatically plots a ZigZag line following swing highs and lows, filtered by a customizable look-back length, helping to remove minor “noise” and highlight true structural pivots.
Labels each significant high or low as HH, HL, LH, or LL, enabling instant recognition of bullish or bearish market conditions.
Distinguishes structural shifts (“Break of Structure,” or BOS) with optional colored bar backgrounds for enhanced visual clarity when trends change.
Offers flexible controls over line color, width, label visibility and size, making it adaptable for different charting styles and timeframes.
Features and Customization
ZigZag Settings: Choose your preferred length and visual styling to fine-tune swing detection, with the ability to show or hide zigzag lines and adjust colors and thickness.
Labeling Structure: Toggle on/off the display of HH/HL/LH/LL labels, with customizable text size, helping you focus on the information relevant to your strategy.
Breakout Confirmation (Fib Factor): Integrates Fibonacci factor logic for validating when a breakout (BOS) should be recognized, giving added confidence in market turns.
Bar Coloring: Automatically paints bars to match current market bias (bullish or bearish), highlighting moments of structural change for quicker response.
How it Helps Traders
Clarifies Trend Structure: Makes it simple to distinguish trend direction and strength at a glance, improving timing and confidence in trade decisions.
Ideal for Strategy Building: Supports a variety of market-structure-based trading strategies, such as trend continuation, reversal setups, and breakout confirmations.
Saves Analysis Time: Automates the complex process of marking and tracking price swings, so you can focus on execution and risk management.
This indicator offers powerful market structure visualization and analysis, suited for all levels of traders and especially those who use price-action and swing-based systems (Supply & Demand).
Statistical Projection over N Days (drift + σ) – v1.2 [EN]🧭 Overview
“Statistical Projection over N Days (drift + σ)” is a quantitative forecasting model that estimates the expected future price range of any asset over a chosen horizon (default = 10 days).
It combines average drift (trend direction) and historical volatility (σ) to produce a probabilistic cone of future price movement.
The indicator displays:
a blue dashed line (expected price path),
1σ / 2σ deviation bands (volatility envelopes),
and a summary table with the key forecast values and expected return.
⚙️ Core Logic (Explained Simply)
The indicator analyses recent price behavior to estimate two key elements:
the average daily tendency of the market (called drift), and
the average daily variability (called volatility).
Here’s how it works, step by step:
Measures daily percentage changes (using logarithmic returns) to understand how much the price typically moves from one bar to the next.
It then calculates the average of those returns over a chosen historical window (for example, 70 bars).
If the average is positive → the market has a rising tendency (upward drift).
If the average is negative → the market tends to decline (downward drift).
At the same time, it computes the standard deviation of those returns — this shows how “wide” the movements are, i.e. how volatile the asset is.
Using these two measures — drift and volatility — it estimates where the price is statistically expected to move over the next N bars:
The mean projection (blue dashed line) represents the most likely price path.
The 1σ and 2σ lines (teal and gray) define confidence zones, where price is expected to remain about 68% and 95% of the time, respectively.
The model updates continuously with every new bar, recalculating both drift and volatility, so the projection cone expands, contracts, or changes direction depending on the latest market behavior.
📉 Interpretation of the Blue Line
The blue dashed line (pMean) is the statistical forecast path of price over the next N bars.
🔹 When the blue line is below the current price
The recent drift (average log return) is negative → the model expects a gradual decline.
Interpretation:
The prevailing statistical bias is bearish — the market is expected to move lower toward equilibrium.
🔹 When the blue line is above the current price
The recent drift is positive → the model expects a continued rise.
Interpretation:
The price is statistically likely to trend upward, maintaining momentum in the direction of the current drift.
🔹 When the blue line is sloping upward
The mean projection pMean is rising with each new bar.
Indicates positive drift → the average daily return is positive.
Interpretation:
The asset is in a growth phase; volatility bands act as potential expansion corridors.
🔹 When the blue line is sloping downward
The mean projection pMean decreases bar after bar.
Indicates negative drift → average daily return is negative.
Interpretation:
The asset is in a corrective or declining phase, with volatility determining potential drawdown limits.
🔹 When the blue line is flat
The drift (μ) is approximately zero.
Interpretation:
The model sees no directional bias; price equilibrium dominates.
Expect a sideways range unless new volatility (σ) expansion occurs.
📈 How to Read the Entire Projection
Blue dashed line → expected mean path (most probable price trajectory).
Teal lines (±1σ) → statistically normal range (≈68% of future outcomes).
Gray lines (±2σ) → extreme bounds (≈95% of outcomes).
Labels on the right show exact forecast prices for each band.
If the actual price moves outside the gray 2σ range →
→ it signals volatility breakout or regime shift, meaning the past volatility no longer explains the present movement.
🧮 Summary Table
Located at the top-right corner, it provides:
Field Description
Projection (days) Number of bars used for projection (h).
Anchor price Starting close used for forecast.
Mean target (h) Expected price after h bars (blue line endpoint).
1σ Band (↓ / ↑) 68% confidence interval.
2σ Band (↓ / ↑) 95% confidence interval.
Expected return Projected % change from current close to mean target.
Colors can be customized — for example:
white headers,
aqua for anchor price,
lime for target,
orange/red for σ bands,
yellow for expected return.
🧠 Practical Meaning
Blue Line State Interpretation Bias
Above price, rising Ongoing positive drift Bullish
Below price, falling Negative drift Bearish
Flat, near price Neutral drift Sideways
Steep slope Strong directional momentum Trend confirmation
Price > +2σ band Excess volatility / overextension Possible correction
Price < −2σ band Undervaluation or panic Reversion likely
⚡ Summary
Aspect Description
Purpose Statistical forecast of expected price range
Method Drift (μ) + Volatility (σ) from log returns
Outputs Mean projection (blue), 1σ & 2σ bands, expected return
Interpretation Directional bias from blue line and its slope
Recommended timeframe Daily
Best use Trend confirmation, probabilistic target estimation, volatility analysis.
Trade History Label Display On Chart (Copy-paste from Rakuten)Overview
This script automatically displays buy/sell labels on the chart simply by copying and pasting your trade history (execution records) exported from Rakuten Securities in Excel format.
It also automatically calculates the profit and loss for each trade.
Background
When reviewing one’s trades, manually matching the broker’s execution records — “date, time, symbol, number of shares, buy or sell” — with the exact points on the chart can be extremely time-consuming.
This is especially inefficient for day traders and scalpers, who may execute dozens of trades per day.
With this script, you can automatically display the entry (IN) and exit (OUT) points on your chart as labels.
It’s also useful when attaching charts to your trading notes or journals, as you can visually confirm exactly where you entered and exited, greatly speeding up the review process.
The script also supports multiple symbols.
Even if you paste a combined dataset containing trades for several stocks, only the trades for the currently displayed symbol will appear automatically.
This allows you to maintain a single master record and instantly visualize the relevant trades just by switching charts.
How to Use
1. Preparing your Excel data
(1)Export trade history
Export your trade history as a CSV file from Rakuten Securities MarketSpeed II, etc.
If you want to include detailed execution times (seconds), make sure to export the data on the same day.
If you export later as a batch, only the date will remain — the time information (hh:mm:ss) will be lost.
(2)Open and format in Excel
Always open the CSV file in Excel — not in Notepad.
If opened in Notepad, double quotes (") will be automatically added, which makes the script unable to recognize the data correctly.
If you need to include seconds in the execution date/time, set a custom format in Excel as follows:
yyyy/mm/dd hh:mm:ss
Copy the range from Execution Date (Column A) to Execution Price (Column L).
Do not include header rows.
Copy data only. Including the header line will cause parsing errors in the script.
(3)If you create a memo column
You can add a Memo column (Column M) next to the “Execution Price” column.
Anything written here (e.g., trade reasoning or notes) will appear on the chart labels.
If you add a memo column, copy the range from Execution Date (A) to Memo (M) when pasting into the script.
Again, copy only the data (not headers). Including column names will cause errors.
2. Paste data into TradingView
Open the script settings and paste the copied data into the text area labeled “Trade Data Paste Area.”
The script automatically parses the text and recognizes date, time, symbol, trade type, position type, credit type, quantity, price, and memo, displaying them as labels at the correct bar.
You can paste data for multiple stocks at once.
Only the rows matching the currently displayed chart’s symbol will be plotted.
3. Display settings (ON/OFF controls)
Each label element (credit type, position type, quantity, memo, etc.) can be turned ON/OFF individually in the script settings via checkboxes (input.bool).
If you’ve created a memo column, its content will also appear on the label.
4. Checking on the chart
Each trade’s entry and exit are shown directly above or below the relevant candlestick.
You can switch between daily and intraday timeframes for more detailed inspection.
Labels are color-coded (e.g., Buy / Sell / Settlement) for quick visual recognition.
When switching symbols, only the relevant trade labels for that symbol will automatically appear.
5. Notes
The script is designed for use on 1-minute to daily charts.
If there’s no matching candlestick for a given trade date/time, the label may not display correctly.
Data input is manual paste only (automatic import not supported).
CSV files must be edited in Excel. Other editors may alter the text format, causing parsing errors.
Due to Pine Script limitations, input.text_area can hold a maximum of 40,960 characters.
The script is tailored for Rakuten Securities’ export format.
Using data from other brokers may require aligning column structures.
If Rakuten changes its export format, the script may need adjustment.
--------------------------------------------------------------------------------------------
概要
このスクリプトは、楽天証券の約定履歴(取引記録)をExcelからコピーして貼り付けるだけで、チャート上に売買ラベルを自動表示するツールです。
また、各取引の損益も自動で計算されます。
背景
自分のトレードを振り返る際、証券会社の約定記録から「何月何日何時何分、どの銘柄を、何株、買った・売った」を確認して、チャート上の位置と突き合わせる作業は非常に時間がかかります。
特にデイトレードやスキャルピングをしていると、1日に数十件以上の約定が発生し、手動で位置を確認するのは非効率です。
このスクリプトを使えば、IN・OUTのタイミングをチャート上にラベルとして自動表示できます。
自分のトレードノート、トレード日記にチャート画像を貼り付ける際も利用 でき、チャートのどこでエントリー/決済したかを視覚的に確認できるため、振り返り作業が大幅に効率化されます。
また、 複数銘柄に対応しており、貼り付けたデータの中から現在表示中のチャート銘柄と一致する売買履歴だけを抽出・表示します。
これにより、複数銘柄分の約定記録を一括管理していても、チャートを切り替えるだけで該当銘柄の取引履歴を瞬時に可視化できます。
使用方法
1. Excelデータの準備
(1)約定履歴のエクスポート
楽天証券マーケットスピードⅡなどから約定履歴をCSV形式でエクスポートします。
約定の詳細な時刻(時分秒単位)データを取得したい場合は、必ず当日中にエクスポートしてください。後日まとめて過去分をエクスポートしても、日付までしか記録されず、時刻情報(hh:mm:ss)は失われます。
(2)Excelで開いて整形
CSVは必ずExcelで開いて編集してください。メモ帳で開くと "(ダブルクォーテーション) が自動的に付与され、スクリプトが正しく認識できません。
約定日の秒単位までを扱いたい場合は、Excelのセル書式設定を開き、「ユーザー定義」で次の形式を新規作成して適用します。書式を変更しないでコピーした場合は分までのデータとなり、スクリプトは00秒と認識します。
yyyy/mm/dd hh:mm:ss
約定日(A列)~約定単価(L列)までのデータ部分をコピーする。
※このとき、項目名(ヘッダー行)は含めず、データ部分のみをコピーしてください。項目名を含めるとスクリプトが誤認識してエラーになります
(3)メモ欄を作成する場合
約定単価の右隣の列(M列)を「メモ欄」として利用できます。ここにエントリー根拠など任意のメモを書いておくとラベル上でもメモを確認できます。
メモ欄を作成した場合は、約定日(A列)からメモ欄(M列)までをコピーして貼り付けてください。
※このとき、項目名(ヘッダー行)は含めず、データ部分のみをコピーしてください。項目名を含めるとスクリプトが誤認識してエラーになります。
2. データをTradingViewに貼り付ける
スクリプトの設定画面を開き、「取引データ貼り付け欄」にExcelからコピーしたデータをそのまま貼り付けます。
スクリプトが自動でテキストを解析し、日付・時刻・銘柄コード・取引区分・建玉区分・信用区分・数量・単価・メモなどを認識して、ラベルをチャート上に自動配置します。
複数銘柄のデータを一度に貼り付けても問題ありません。現在表示中のチャート銘柄と一致する行だけがラベルとして描画されます。
3. 表示設定(ON/OFF切り替え)
各表示要素(信用区分・建玉区分・数量・メモなど)は、設定画面のチェックボックス(input.bool)で個別に表示/非表示を切り替えられます。
メモ欄を作成している場合は、その内容もラベルに表示されます。
4. チャートでの確認
各取引のIN・OUTが、チャート上の該当バー(ローソク足)にラベルとして表示されます。
日足・分足を切り替えることで、より詳細なタイミングを確認できます。
ラベルは、買い(Buy)・売り(Sell)・返済などで色分けされ、視覚的に理解しやすい構成になっています。
チャートを銘柄ごとに切り替えるだけで、その銘柄の取引履歴のみが自動表示されます。
5. 注意点
このスクリプトは 1分足~日足 での使用を想定しています。データ上の日付や時刻に対応するローソク足が存在しない場合、ラベルを正しく表示できません。
データは手動貼り付け方式です。自動取得には対応していません。
Excel以外のアプリで開いたCSVは、文字列形式が変わるため解析できないことがあります。
Pineスクリプトの仕様上、テキストエリアには40,960文字までしか貼り付けできません。
楽天証券の出力フォーマットを想定しているため、他社形式を使う場合は列構成を揃える必要があります。
また、楽天証券の出力フォーマットが変更された場合は、正しく表示出来なります。
Symmetry Break Index | QRSymmetry Break Trend Scanner | QuantumResearch
What it does
This indicator detects trend regime shifts by measuring how persistently price deviates from its moving-average “symmetry.” It outputs a continuous Score and a binary Signal (Bullish / Bearish) when that score crosses user-defined thresholds:
Bullish (Long) when upside deviations dominate → sustained uptrend bias
Bearish (Short/Cash) when downside deviations dominate → sustained downtrend bias
It’s built for clarity and consistency: the plot is a single score with two horizontal decision lines so traders can quickly identify regime changes on a clean chart.
How it works (principle, not code)
Normalize price vs trend: Price is standardized against a moving average and its standard deviation to create a dimensionless “oscillator” series (how far above/below typical behavior price sits).
Symmetry count: For a user-defined range of reference levels, the script counts whether the standardized price is above or below each level. This builds a cumulative symmetry score: positive when upside presence is broad and persistent, negative when downside dominates.
Regime thresholds: Crossing the Uptrend Threshold or Downtrend Threshold flips the quantum state to Bullish or Bearish, minimizing noise compared with a single-level trigger.
This approach emphasizes persistence and breadth of deviation rather than one-off spikes, which can help filter chop.
Plots & visuals
Score (histogram/area fill): Positive area fills in the bullish color, negative area in the bearish color.
Zero line: Quick reference for balance between up/down deviations.
Two decision lines: Uptrend Threshold and Downtrend Threshold to mark regime flips.
Bar colors: Bars tint with the active regime (Bullish / Bearish) for fast reads.
Publish with a clean chart so the score and thresholds are clearly visible. Avoid extra indicators unless they are required and explained.
Inputs & customization
MA Length (default 40): Window for the baseline moving average and volatility. Shorter = more reactive; longer = smoother.
Source: Price input (e.g., close).
For Loop Range (Start / End, default −200…200): Breadth of reference levels in the symmetry count. Wider range = stronger smoothing and slower flips.
Uptrend / Downtrend Thresholds: Regime triggers. Tighten to react faster, widen to reduce whipsaws.
Color Mode: Choose a palette to match your chart.
Tip: Start with defaults, then tune MA Length and thresholds for your market/timeframe.
How to use it
Trend confirmation: Trade in the direction of the active regime; avoid counter-trend setups when the score is far beyond a threshold.
Risk controls: When the score retreats toward zero, consider reducing size or tightening stops—momentum is weakening.
Confluence: Combine with structure (S/R), volume, or volatility bands for entries/exits; the score provides context, not entries alone.
Originality & value
Unlike single-threshold oscillators, this method aggregates many standardized comparisons into one score, rewarding persistence and breadth of deviation. The result is a robust regime signal that tends to filter fleeting wiggles and highlight true symmetry breaks.
Limitations
Extremely range-bound markets can still produce false flips if thresholds are too tight.
Sudden volatility regime changes may require re-tuning MA Length or thresholds.
Standardization depends on the chosen window; there is no “one size fits all.”
Disclaimer
This tool is for research/education and is not financial advice. Markets involve risk, including loss of capital. Past performance does not predict or guarantee future results. Always test settings on your timeframe and use prudent risk management.
BTC Futures Open Interest 7-day Change | QRBitcoin Futures OI vs Price (7-Day)
What it is
This tool compares the 7-day momentum of Bitcoin perpetual futures Open Interest (OI) with the 7-day price change to classify market behavior into four intuitive regimes:
Leverage Rally (OI↑, Price↑) – positioning builds with rising price
Leveraged Sell-Off (OI↑, Price↓) – forced/short-term positioning into weakness
Deleveraging Sell-Off (OI↓, Price↓) – positions reduce while price falls
Spot Rally (OI↓, Price↑) – spot-led advance with lighter derivatives leverage
It is designed for BTC using the BINANCE:BTCUSD.P OI feed and a clean, self-contained visualization.
How it works (principle, not code)
OI Momentum: Calculates the 7-day Rate of Change (ROC) of BTC perpetual futures Open Interest.
Price Momentum: Calculates the 7-day ROC of the chart’s close.
Regime Logic: The sign of OI ROC and Price ROC determines the 4 regimes shown in the on-chart table label.
Volatility Context: A rolling standard deviation of OI ROC defines ±1σ and ±2σ bands. Bars are tinted when OI ROC exceeds ±2σ to highlight exceptional leverage shifts.
This is not a latency-sensitive microstructure model; it’s a context tool to see how derivatives positioning evolves relative to price.
Why it’s useful (originality & value)
Most OI overlays show a single line. This script adds:
a behavioral classifier (the 4 regimes) that’s immediately interpretable, and
adaptive σ-bands on OI momentum to distinguish routine leverage changes from abnormal expansions/flushes.
Together, they make it easier to read leverage cycles, spot rally quality, and identify riskier states (e.g., price up while OI surges vs. price up while OI fades).
What you see on the chart
Futures Open Interest (stepline) for BTC perpetuals (BINANCE:BTCUSD.P_OI).
OI ROC plot with zero line and ±1σ / ±2σ guides.
Bar tinting when OI ROC > +2σ (aggressive leverage build) or < −2σ (aggressive deleveraging).
Side table showing current OI ROC, Price ROC, and the regime label.
Note: If applied to a non-crypto symbol, OI will be suppressed and the script will warn that no OI data is available. It is intended for BTC.
Inputs & customization
Color mode: Choose among preset palettes to match your chart style.
(Other logic—lookbacks, σ-bands, and regime rules—are fixed to keep the reading consistent across users.)
How to use it
Confirm trends:
Leverage Rally with OI ROC above +1σ supports risk-on continuation.
Spot Rally can be constructive early in cycles, but be aware that OI can catch up quickly.
Caution in stress:
Leveraged Sell-Off often coincides with liquidation spikes and unstable conditions.
Deleveraging Sell-Off typically marks clearing phases; watch for stabilization as OI ROC returns toward 0.
Watch extremes:
±2σ moves in OI ROC are non-routine; combine with price structure, liquidations, and funding to refine decisions.
Use it as contextual confluence alongside your execution plan (levels, risk, and timeframe).
Chart-publishing guidance
Publish with a clean chart so the OI line, ROC bands, and regime label are easy to identify.
Avoid stacking unrelated indicators unless you explain why they are required to interpret the tool.
Limitations
OI feeds can vary by venue; this script uses Binance perpetual OI. Other venues may differ.
Short-term spikes (maintenance, outages, large block flows) can distort OI ROC for a few bars.
The σ-bands adapt to recent variability; regime persistence is more informative than a single spike.
Disclaimer
This script is for research and educational purposes only and is not financial advice. Trading involves risk, including loss of capital. Past performance does not predict or guarantee future results. Always validate on your timeframe and use robust risk management.
AASI | QRAASI | QR — Active Address Sentiment Index
What it is
AASI | QR is a market activity gauge that compares on-chain participation (Active Addresses) with price momentum. It highlights regimes where network usage accelerates/decelerates relative to price and uses adaptive bands to flag expansions that may precede trend continuation or fade. Designed for BTC (and any symbol with an “Active Addresses” feed), it provides clear, visual context rather than trade calls.
How it works (principle, not code)
Active Address Momentum (core signal)
The script measures the rate of change (ROC) of Active Addresses and builds dynamic, volatility-scaled bands around zero. When address momentum pushes into progressively higher (or lower) bands, it reflects broadening (or narrowing) participation.
Price Momentum Overlay (context)
A price ROC runs alongside address momentum so you can visually compare participation vs. price. This helps distinguish healthy trend strength (price rising with rising participation) from potential exhaustion (diverging behavior).
Adaptive Bands (regimes)
Bands (±1×, ±2×, ±3× of the dynamic scale) expand/contract with recent variability in address momentum. The background tint optionally highlights strong expansions:
• Upper expansions → potential risk-on phases
• Lower expansions → potential risk-off phases
No fixed overbought/oversold thresholds are hard-coded; the bands adapt to the current regime, which helps keep the tool relevant across market phases.
Why this is useful (originality & value)
Most momentum overlays watch price alone. AASI adds a behavioral layer by tracking how many participants are active while price moves. This helps:
Separate euphoric spikes (price up, participation flat/falling) from broad advance (price up, participation rising).
Spot early cooling (participation momentum fades before price) and late accelerations (fresh participation kick).
Maintain clarity via adaptive scaling, so signals don’t go “permanently stretched” in strong cycles.
What you see on the chart
Zero Baseline with three up/down bands (±1, ±2, ±3).
Active Address ROC (soft line, main signal).
Price ROC (overlay line for context).
Optional background tint when price ROC reaches the upper or lower adaptive zones.
Clean presentation: the script is self-contained and readable without other overlays.
Inputs & customization
Bands & Trend: toggle visibility of ±1/±2/±3 bands.
Active Address & Price: toggle the address ROC and price ROC plots.
Color Mode: switch palettes to match your layout.
Lookbacks: the internal dynamic scaling is derived from recent variability of address momentum (kept simple for usability).
How to use it
Confluence: Look for price ROC and address ROC moving in the same direction and entering higher bands → strengthens the risk-on case.
Divergence: Price pushing higher while address ROC stalls or falls toward lower bands → participation not confirming; be cautious.
Regime shifts: When address ROC crosses the zero line and sustains inside ±1/±2 bands, it often marks a state change (cooling → heating or vice-versa).
Combine responsibly: Use with your risk framework (position sizing, stops). AASI is context, not an auto-trader.
Scope & data notes
Designed for BTC with a GLASSNODE:BTC_ACTIVEADDRESSES series.
Can be applied to other assets only if a comparable “Active Addresses” feed exists for that symbol. If no feed is present, use price ROC alone just for context (reduced informational value).
The script relies on close-form series provided on TradingView; no external links or delegation required to interpret its purpose.
Chart-publishing guidance
Publish with a clean chart showing only AASI to keep outputs identifiable.
If you add drawings, use them strictly to illustrate where participation confirmed or diverged from price.
Limitations
On-chain participation data can be noisy around events, holidays, or network anomalies.
Adaptive bands reflect recent variability; sudden structural changes may require time to re-scale.
Not a buy/sell system; it’s a diagnostic layer for regime awareness and confirmation.
Disclaimer
This tool is for research and educational purposes only and is not financial advice. Trading and investing involve risk, including loss of capital. Past performance does not predict or guarantee future results. Always validate settings on your timeframe and use proper risk management.
HTF Candles with PVSRA Volume Coloring (PCS Series)This indicator displays higher timeframe (HTF) candles using a PVSRA-inspired color model that blends price and volume strength, allowing traders to visualize higher-timeframe activity directly on lower-timeframe charts without switching screens.
OVERVIEW
This script visualizes higher-timeframe (HTF) candles directly on lower-timeframe charts using a custom PVSRA (Price, Volume & Support/Resistance Analysis) color model.
Unlike standard HTF indicators, it aggregates real-time OHLC and volume data bar-by-bar and dynamically draws synthetic HTF candles that update as the higher-timeframe bar evolves.
This allows traders to interpret momentum, trend continuation, and volume pressure from broader market structures without switching charts.
INTEGRATION LOGIC
This script merges higher-timeframe candle projection with PVSRA volume analysis to provide a single, multi-timeframe momentum view.
The HTF structure reveals directional context, while PVSRA coloring exposes the underlying strength of buying and selling pressure.
By combining both, traders can see when a higher-timeframe candle is building with strong or weak volume, enabling more informed intraday decisions than either tool could offer alone.
HOW IT WORKS
Aggregates price data : Groups lower-timeframe bars to calculate higher-timeframe Open, High, Low, Close, and total Volume.
Applies PVSRA logic : Compares each HTF candle’s volume to the average of the last 10 bars:
• >200% of average = strong activity
• >150% of average = moderate activity
• ≤150% = normal activity
Assigns colors :
• Green/Blue = bullish high-volume
• Red/Fuchsia = bearish high-volume
• White/Gray = neutral or low-volume moves
Draws dynamic outlines : Outlines update live while the current HTF candle is forming.
Supports symbol override : Calculations can use another instrument for correlation analysis.
This multi-timeframe aggregation avoids repainting issues in request.security() and ensures accurate real-time HTF representation.
FEATURES
Dual HTF Display : Visualize two higher timeframes simultaneously (e.g., 4H and 1D).
Dynamic PVSRA Coloring : Volume-weighted candle colors reveal bullish or bearish dominance.
Customizable Layout : Adjust candle width, spacing, offset, and color schemes.
Candle Outlines : Highlight the forming HTF candle to monitor developing structure.
Symbol Override : Display HTF candles from another instrument for cross-analysis.
SETTINGS
HTF 1 & HTF 2 : enable/disable, set timeframes, choose label colors, show/hide outlines.
Number of Candles : choose how many HTF candles to plot (1–10).
Offset Position : distance to the right of the current price where HTF candles begin.
Spacing & Width : adjust separation and scaling of candle groups.
Show Wicks/Borders : toggle wick and border visibility.
PVSRA Colors : enable or disable volume-based coloring.
Symbol Override : use a secondary ticker for HTF data if desired.
USAGE TIPS
Set the indicator’s visual order to “Bring to front.”
Always choose HTFs higher than your active chart timeframe.
Use PVSRA colors to identify strong momentum and potential reversals.
Adjust candle spacing and width for your chart layout.
Outlines are not shown on chart timeframes below 5 minutes.
TRADING STRATEGY
Strategy Overview : Combine HTF structure and PVSRA volume signals to
• Identify zones of high institutional activity and potential reversals.
• Wait for confirmation through consolidation or a pullback to key levels.
• Trade in alignment with dominant higher-timeframe structure rather than chasing volatility.
Setup :
• Chart timeframe: lower (5m, 15m, 1H)
• HTF 1: 4H or 1D
• HTF 2: 1D or 1W
• PVSRA Colors: enabled
• Outlines: enabled
Entry Concept :
High-volume candles (green or red) often indicate market-maker activity , such zones often reflect liquidity absorption by larger players and are not necessarily ideal entry points.
Wait for the next consolidation or pullback toward a support or resistance level before acting.
Bullish scenario :
• After a high-volume or rejection candle near a low, price consolidates and forms a higher low.
• Enter long only when structure confirms strength above support.
Bearish scenario :
• After a high-volume or rejection candle near a top, price consolidates and forms a lower high.
• Enter short once resistance holds and momentum weakens.
Exit Guidelines :
• Exit when next HTF candle shifts in color or momentum fades.
• Exit if price structure breaks opposite to your trade direction.
• Always use stop-loss and take-profit levels.
Additional Tips :
• Never enter directly on strong green/red high-volume candles, these are usually areas of institutional absorption.
• Wait for market structure confirmation and volume normalization.
• Combine with RSI, moving averages, or support/resistance for timing.
• Avoid trading when HTF candles are mixed or low-volume (unclear bias).
• Outlines hidden below 5m charts.
Risk Management :
• Use stop-loss and take-profit on all positions.
• Limit risk to 1–2% per trade.
• Adjust position size for volatility.
FINAL NOTES
This script helps traders synchronize lower-timeframe execution with higher-timeframe momentum and volume dynamics.
Test it on demo before live use, and adjust settings to fit your trading style.
DISCLAIMER
This script is for educational purposes only and does not constitute financial advice.
SUPPORT & UPDATES
Future improvements may include alert conditions and additional visualization modes. Feedback is welcome in the comments section.
CREDITS & LICENSE
Created by @seoco — open source for community learning.
Licensed under Mozilla Public License 2.0 .
Mean Reversion Oscillator [Alpha Extract]An advanced composite oscillator system specifically designed to identify extreme market conditions and high-probability mean reversion opportunities, combining five proven oscillators into a single, powerful analytical framework.
By integrating multiple momentum and volume-based indicators with sophisticated extreme level detection, this oscillator provides precise entry signals for contrarian trading strategies while filtering out false reversals through momentum confirmation.
🔶 Multi-Oscillator Composite Framework
Utilizes a comprehensive approach that combines Bollinger %B, RSI, Stochastic, Money Flow Index, and Williams %R into a unified composite score. This multi-dimensional analysis ensures robust signal generation by capturing different aspects of market extremes and momentum shifts.
// Weighted composite (equal weights)
normalized_bb = bb_percent
normalized_rsi = rsi
normalized_stoch = stoch_d_val
normalized_mfi = mfi
normalized_williams = williams_r
composite_raw = (normalized_bb + normalized_rsi + normalized_stoch + normalized_mfi + normalized_williams) / 5
composite = ta.sma(composite_raw, composite_smooth)
🔶 Advanced Extreme Level Detection
Features a sophisticated dual-threshold system that distinguishes between moderate and extreme market conditions. This hierarchical approach allows traders to identify varying degrees of mean reversion potential, from moderate oversold/overbought conditions to extreme levels that demand immediate attention.
🔶 Momentum Confirmation System
Incorporates a specialized momentum histogram that confirms mean reversion signals by analyzing the rate of change in the composite oscillator. This prevents premature entries during strong trending conditions while highlighting genuine reversal opportunities.
// Oscillator momentum (rate of change)
osc_momentum = ta.mom(composite, 5)
histogram = osc_momentum
// Momentum confirmation
momentum_bullish = histogram > histogram
momentum_bearish = histogram < histogram
// Confirmed signals
confirmed_bullish = bullish_entry and momentum_bullish
confirmed_bearish = bearish_entry and momentum_bearish
🔶 Dynamic Visual Intelligence
The oscillator line adapts its color intensity based on proximity to extreme levels, providing instant visual feedback about market conditions. Background shading creates clear zones that highlight when markets enter moderate or extreme territories.
🔶 Intelligent Signal Generation
Generates precise entry signals only when the composite oscillator crosses extreme thresholds with momentum confirmation. This dual-confirmation approach significantly reduces false signals while maintaining sensitivity to genuine mean reversion opportunities.
How It Works
🔶 Composite Score Calculation
The indicator simultaneously tracks five different oscillators, each normalized to a 0-100 scale, then combines them into a smoothed composite score. This approach eliminates the noise inherent in single-oscillator analysis while capturing the consensus view of multiple momentum indicators.
// Mean reversion entry signals
bullish_entry = ta.crossover(composite, 100 - extreme_level) and composite < (100 - extreme_level)
bearish_entry = ta.crossunder(composite, extreme_level) and composite > extreme_level
// Bollinger %B calculation
bb_basis = ta.sma(src, bb_length)
bb_dev = bb_mult * ta.stdev(src, bb_length)
bb_percent = (src - bb_lower) / (bb_upper - bb_lower) * 100
🔶 Extreme Zone Identification
The system automatically identifies when markets reach statistically significant extreme levels, both moderate (65/35) and extreme (80/20). These zones represent areas where mean reversion has the highest probability of success based on historical market behavior.
🔶 Momentum Histogram Analysis
A specialized momentum histogram tracks the velocity of oscillator changes, helping traders distinguish between healthy corrections and potential trend reversals. The histogram's color-coded display makes momentum shifts immediately apparent.
🔶 Divergence Detection Framework
Built-in divergence analysis identifies situations where price and oscillator movements diverge, often signaling impending reversals. Diamond-shaped markers highlight these critical divergence patterns for enhanced pattern recognition.
🔶 Real-Time Information Dashboard
An integrated information table provides instant access to current oscillator readings, market status, and individual component values. This dashboard eliminates the need to manually check multiple indicators while trading.
🔶 Individual Component Display
Optional display of individual oscillator components allows traders to understand which specific indicators are driving the composite signal. This transparency enables more informed decision-making and deeper market analysis.
🔶 Adaptive Background Coloring
Intelligent background shading automatically adjusts based on market conditions, creating visual zones that correspond to different levels of mean reversion potential. The subtle color gradations make pattern recognition effortless.
1D
3D
🔶 Comprehensive Alert System
Multi-tier alert system covers confirmed entry signals, divergence patterns, and extreme level breaches. Each alert type provides specific context about the detected condition, enabling traders to respond appropriately to different signal strengths.
🔶 Customizable Threshold Management
Fully adjustable extreme and moderate levels allow traders to fine-tune the indicator's sensitivity to match different market volatilities and trading timeframes. This flexibility ensures optimal performance across various market conditions.
🔶 Why Choose AE - Mean Reversion Oscillator?
This indicator provides the most comprehensive approach to mean reversion trading by combining multiple proven oscillators with advanced confirmation mechanisms. By offering clear visual hierarchies for different extreme levels and requiring momentum confirmation for signals, it empowers traders to identify high-probability contrarian opportunities while avoiding false reversals. The sophisticated composite methodology ensures that signals are both statistically significant and practically actionable, making it an essential tool for traders focused on mean reversion strategies across all market conditions.
Filter Signal 5🧭 Overview
“Filter Signal 5.0” is a professional confirmation and filtering tool designed to validate the true directional bias of any asset.
It combines price structure, volume dynamics, oscillator alignment, and multi-timeframe confirmation to detect high-probability directional setups while blocking false counter-trend signals.
The indicator calculates a directional score (0–4) based on the confluence of several technical conditions and displays both the current trend and the higher-timeframe trend in a compact on-chart dashboard.
⚙️ Core Logic
The indicator integrates four major analytical pillars:
Component Description Purpose
VWMA Trend Compares price to the Volume-Weighted Moving Average (VWMA 20). Detects the base trend (above = bullish, below = bearish).
Volume Flow Evaluates direction (buy/sell) and trend (rising/falling) of volume. Confirms institutional participation.
RSI Extreme Cross RSI crossing its SMA in extreme zones (<27 or >80). Identifies momentum reversals with statistical strength.
Oscillator Concordance Combines 3 signals (Stochastic, Fisher Transform, Williams %R). Measures broad technical consensus.
Each bullish or bearish confirmation adds +1 point to its respective score.
The final output is the comparison between scoreLong and scoreShort.
🧩 Multi-Timeframe Filter (MTF)
A higher-timeframe VWMA (e.g., Weekly or Monthly) is imported through request.security().
If the higher-timeframe trend is UP, bearish scores are suppressed.
If the higher-timeframe trend is DOWN, bullish scores are suppressed.
✅ This ensures entries are only taken in the direction of the dominant market trend.
🎯 Forecast Target System
Each new bar automatically generates a static forecast target (varip) based on the 10-bar average range:
If bullish → target = close + avgRange
If bearish → target = close − avgRange
This level is drawn as a yellow dashed line, providing a short-term statistical price projection.
🧮 Directional Logic Summary
Condition Weight Effect
Price > VWMA +1 Long Trend confirmation
Volume rising in buy candles +1 Long Institutional strength
RSI cross < 27 +1 Long Reversal signal
2 / 3 oscillators in buy mode +1 Long Statistical agreement
Mirror logic applies for short signals.
Final bias is determined by comparing total long vs short scores.
📊 Dashboard Information
Displayed at the bottom-left corner of the chart:
Field Meaning
📊 Trend Now Current directional bias (📈 UP / 📉 DOWN / ➡ NEUTRAL)
🎯 Forecast Target Predicted price level for the current bar
⏱ Filter MTF Higher timeframe used for filtering (e.g., W, 1M)
📐 Trend MTF Trend status of the higher timeframe
The dashboard updates dynamically on each bar close.
⚠️ Alerts
Two automatic alerts are available:
⚠️ Strong Buy: when scoreLong ≥ 3
⚠️ Strong Sell: when scoreShort ≥ 3
These appear only when at least three technical components agree.
📈 How to Use It
Load the indicator on your preferred asset and timeframe (recommended: Daily).
Set the higher timeframe filter (tf_selezione) → use “W” (Weekly) or “1M” (Monthly) for institutional alignment.
Wait for full confirmation:
Trend Now = 📈 UP and Trend MTF = 📈 UP → Long setup confirmed
Trend Now = 📉 DOWN and Trend MTF = 📉 DOWN → Short setup confirmed
Avoid trading when:
Trends are misaligned (different directions).
Score is < 2 / 4 (neutral zone).
🧠 Trading Logic Summary
Scenario Requirements Action
Long Setup Score ≥ 3 and MTF trend = UP Enter or hold long position
Short Setup Score ≥ 3 and MTF trend = DOWN Enter or hold short position
Neutral Mixed signals / MTF mismatch Stay flat – wait for breakout
🧮 Practical Example
When the daily timeframe prints 📈 Trend Now = UP, and the weekly filter shows 📐 Trend MTF = UP, the system has full alignment.
The yellow dashed line projects the short-term target for the move.
If volume direction and oscillators confirm, an alert “⚠️ Strong Buy” is automatically triggered.
✅ Ideal Usage
This indicator is designed to work together with Lanfranco’s other institutional models, such as:
TSI-RSI-ATR Dashboard → internal momentum and volatility,
Institutional Module / Smart Buy-Sell System → predictive divergence and volume compression,
Dynamic Price Targets / Sigma Bands → probabilistic price zones.
The “MTF Filter 4” acts as the final confirmation layer, the traffic-light system:
🟢 Green = confirmed direction,
🔴 Red = blocked signal,
🟠 Orange = neutral wait-state.
⚡ Summary
Type: Multi-factor signal confirmation tool
Core concept: Combine price + volume + oscillators + multi-timeframe filter
Best timeframe: Daily
Typical filter: Weekly or Monthly
Output: Directional bias, short-term forecast, institutional trend alignment
Historical Matrix Analyzer [PhenLabs]📊Historical Matrix Analyzer
Version: PineScriptv6
📌Description
The Historical Matrix Analyzer is an advanced probabilistic trading tool that transforms technical analysis into a data-driven decision support system. By creating a comprehensive 56-cell matrix that tracks every combination of RSI states and multi-indicator conditions, this indicator reveals which market patterns have historically led to profitable outcomes and which have not.
At its core, the indicator continuously monitors seven distinct RSI states (ranging from Extreme Oversold to Extreme Overbought) and eight unique indicator combinations (MACD direction, volume levels, and price momentum). For each of these 56 possible market states, the system calculates average forward returns, win rates, and occurrence counts based on your configurable lookback period. The result is a color-coded probability matrix that shows you exactly where you stand in the historical performance landscape.
The standout feature is the Current State Panel, which provides instant clarity on your active market conditions. This panel displays signal strength classifications (from Strong Bullish to Strong Bearish), the average return percentage for similar past occurrences, an estimated win rate using Bayesian smoothing to prevent small-sample distortions, and a confidence level indicator that warns you when insufficient data exists for reliable conclusions.
🚀Points of Innovation
Multi-dimensional state classification combining 7 RSI levels with 8 indicator combinations for 56 unique trackable market conditions
Bayesian win rate estimation with adjustable smoothing strength to provide stable probability estimates even with limited historical samples
Real-time active cell highlighting with “NOW” marker that visually connects current market conditions to their historical performance data
Configurable color intensity sensitivity allowing traders to adjust heat-map responsiveness from conservative to aggressive visual feedback
Dual-panel display system separating the comprehensive statistics matrix from an easy-to-read current state summary panel
Intelligent confidence scoring that automatically warns traders when occurrence counts fall below reliable thresholds
🔧Core Components
RSI State Classification: Segments RSI readings into 7 distinct zones (Extreme Oversold <20, Oversold 20-30, Weak 30-40, Neutral 40-60, Strong 60-70, Overbought 70-80, Extreme Overbought >80) to capture momentum extremes and transitions
Multi-Indicator Condition Tracking: Simultaneously monitors MACD crossover status (bullish/bearish), volume relative to moving average (high/low), and price direction (rising/falling) creating 8 binary-encoded combinations
Historical Data Storage Arrays: Maintains rolling lookback windows storing RSI states, indicator states, prices, and bar indices for precise forward-return calculations
Forward Performance Calculator: Measures price changes over configurable forward bar periods (1-20 bars) from each historical state, accumulating total returns and win counts per matrix cell
Bayesian Smoothing Engine: Applies statistical prior assumptions (default 50% win rate) weighted by user-defined strength parameter to stabilize estimated win rates when sample sizes are small
Dynamic Color Mapping System: Converts average returns into color-coded heat map with intensity adjusted by sensitivity parameter and transparency modified by confidence levels
🔥Key Features
56-Cell Probability Matrix: Comprehensive grid displaying every possible combination of RSI state and indicator condition, with each cell showing average return percentage, estimated win rate, and occurrence count for complete statistical visibility
Current State Info Panel: Dedicated display showing your exact position in the matrix with signal strength emoji indicators, numerical statistics, and color-coded confidence warnings for immediate situational awareness
Customizable Lookback Period: Adjustable historical window from 50 to 500 bars allowing traders to focus on recent market behavior or capture longer-term pattern stability across different market cycles
Configurable Forward Performance Window: Select target holding periods from 1 to 20 bars ahead to align probability calculations with your trading timeframe, whether day trading or swing trading
Visual Heat Mapping: Color-coded cells transition from red (bearish historical performance) through gray (neutral) to green (bullish performance) with intensity reflecting statistical significance and occurrence frequency
Intelligent Data Filtering: Minimum occurrence threshold (1-10) removes unreliable patterns with insufficient historical samples, displaying gray warning colors for low-confidence cells
Flexible Layout Options: Independent positioning of statistics matrix and info panel to any screen corner, accommodating different chart layouts and personal preferences
Tooltip Details: Hover over any matrix cell to see full RSI label, complete indicator status description, precise average return, estimated win rate, and total occurrence count
🎨Visualization
Statistics Matrix Table: A 9-column by 8-row grid with RSI states labeling vertical axis and indicator combinations on horizontal axis, using compact abbreviations (XOverS, OverB, MACD↑, Vol↓, P↑) for space efficiency
Active Cell Indicator: The current market state cell displays “⦿ NOW ⦿” in yellow text with enhanced color saturation to immediately draw attention to relevant historical performance
Signal Strength Visualization: Info panel uses emoji indicators (🔥 Strong Bullish, ✅ Bullish, ↗️ Weak Bullish, ➖ Neutral, ↘️ Weak Bearish, ⛔ Bearish, ❄️ Strong Bearish, ⚠️ Insufficient Data) for rapid interpretation
Histogram Plot: Below the price chart, a green/red histogram displays the current cell’s average return percentage, providing a time-series view of how historical performance changes as market conditions evolve
Color Intensity Scaling: Cell background transparency and saturation dynamically adjust based on both the magnitude of average returns and the occurrence count, ensuring visual emphasis on reliable patterns
Confidence Level Display: Info panel bottom row shows “High Confidence” (green), “Medium Confidence” (orange), or “Low Confidence” (red) based on occurrence counts relative to minimum threshold multipliers
📖Usage Guidelines
RSI Period
Default: 14
Range: 1 to unlimited
Description: Controls the lookback period for RSI momentum calculation. Standard 14-period provides widely-recognized overbought/oversold levels. Decrease for faster, more sensitive RSI reactions suitable for scalping. Increase (21, 28) for smoother, longer-term momentum assessment in swing trading. Changes affect how quickly the indicator moves between the 7 RSI state classifications.
MACD Fast Length
Default: 12
Range: 1 to unlimited
Description: Sets the faster exponential moving average for MACD calculation. Standard 12-period setting works well for daily charts and captures short-term momentum shifts. Decreasing creates more responsive MACD crossovers but increases false signals. Increasing smooths out noise but delays signal generation, affecting the bullish/bearish indicator state classification.
MACD Slow Length
Default: 26
Range: 1 to unlimited
Description: Defines the slower exponential moving average for MACD calculation. Traditional 26-period setting balances trend identification with responsiveness. Must be greater than Fast Length. Wider spread between fast and slow increases MACD sensitivity to trend changes, impacting the frequency of indicator state transitions in the matrix.
MACD Signal Length
Default: 9
Range: 1 to unlimited
Description: Smoothing period for the MACD signal line that triggers bullish/bearish state changes. Standard 9-period provides reliable crossover signals. Shorter values create more frequent state changes and earlier signals but with more whipsaws. Longer values produce more confirmed, stable signals but with increased lag in detecting momentum shifts.
Volume MA Period
Default: 20
Range: 1 to unlimited
Description: Lookback period for volume moving average used to classify volume as “high” or “low” in indicator state combinations. 20-period default captures typical monthly trading patterns. Shorter periods (10-15) make volume classification more reactive to recent spikes. Longer periods (30-50) require more sustained volume changes to trigger state classification shifts.
Statistics Lookback Period
Default: 200
Range: 50 to 500
Description: Number of historical bars used to calculate matrix statistics. 200 bars provides substantial data for reliable patterns while remaining responsive to regime changes. Lower values (50-100) emphasize recent market behavior and adapt quickly but may produce volatile statistics. Higher values (300-500) capture long-term patterns with stable statistics but slower adaptation to changing market dynamics.
Forward Performance Bars
Default: 5
Range: 1 to 20
Description: Number of bars ahead used to calculate forward returns from each historical state occurrence. 5-bar default suits intraday to short-term swing trading (5 hours on hourly charts, 1 week on daily charts). Lower values (1-3) target short-term momentum trades. Higher values (10-20) align with position trading and longer-term pattern exploitation.
Color Intensity Sensitivity
Default: 2.0
Range: 0.5 to 5.0, step 0.5
Description: Amplifies or dampens the color intensity response to average return magnitudes in the matrix heat map. 2.0 default provides balanced visual emphasis. Lower values (0.5-1.0) create subtle coloring requiring larger returns for full saturation, useful for volatile instruments. Higher values (3.0-5.0) produce vivid colors from smaller returns, highlighting subtle edges in range-bound markets.
Minimum Occurrences for Coloring
Default: 3
Range: 1 to 10
Description: Required minimum sample size before applying color-coded performance to matrix cells. Cells with fewer occurrences display gray “insufficient data” warning. 3-occurrence default filters out rare patterns. Lower threshold (1-2) shows more data but includes unreliable single-event statistics. Higher thresholds (5-10) ensure only well-established patterns receive visual emphasis.
Table Position
Default: top_right
Options: top_left, top_right, bottom_left, bottom_right
Description: Screen location for the 56-cell statistics matrix table. Position to avoid overlapping critical price action or other indicators on your chart. Consider chart orientation and candlestick density when selecting optimal placement.
Show Current State Panel
Default: true
Options: true, false
Description: Toggle visibility of the dedicated current state information panel. When enabled, displays signal strength, RSI value, indicator status, average return, estimated win rate, and confidence level for active market conditions. Disable to declutter charts when only the matrix table is needed.
Info Panel Position
Default: bottom_left
Options: top_left, top_right, bottom_left, bottom_right
Description: Screen location for the current state information panel (when enabled). Position independently from statistics matrix to optimize chart real estate. Typically placed opposite the matrix table for balanced visual layout.
Win Rate Smoothing Strength
Default: 5
Range: 1 to 20
Description: Controls Bayesian prior weighting for estimated win rate calculations. Acts as virtual sample size assuming 50% win rate baseline. Default 5 provides moderate smoothing preventing extreme win rate estimates from small samples. Lower values (1-3) reduce smoothing effect, allowing win rates to reflect raw data more directly. Higher values (10-20) increase conservatism, pulling win rate estimates toward 50% until substantial evidence accumulates.
✅Best Use Cases
Pattern-based discretionary trading where you want historical confirmation before entering setups that “look good” based on current technical alignment
Swing trading with holding periods matching your forward performance bar setting, using high-confidence bullish cells as entry filters
Risk assessment and position sizing, allocating larger size to trades originating from cells with strong positive average returns and high estimated win rates
Market regime identification by observing which RSI states and indicator combinations are currently producing the most reliable historical patterns
Backtesting validation by comparing your manual strategy signals against the historical performance of the corresponding matrix cells
Educational tool for developing intuition about which technical condition combinations have actually worked versus those that feel right but lack historical evidence
⚠️Limitations
Historical patterns do not guarantee future performance, especially during unprecedented market events or regime changes not represented in the lookback period
Small sample sizes (low occurrence counts) produce unreliable statistics despite Bayesian smoothing, requiring caution when acting on low-confidence cells
Matrix statistics lag behind rapidly changing market conditions, as the lookback period must accumulate new state occurrences before updating performance data
Forward return calculations use fixed bar periods that may not align with actual trade exit timing, support/resistance levels, or volatility-adjusted profit targets
💡What Makes This Unique
Multi-Dimensional State Space: Unlike single-indicator tools, simultaneously tracks 56 distinct market condition combinations providing granular pattern resolution unavailable in traditional technical analysis
Bayesian Statistical Rigor: Implements proper probabilistic smoothing to prevent overconfidence from limited data, a critical feature missing from most pattern recognition tools
Real-Time Contextual Feedback: The “NOW” marker and dedicated info panel instantly connect current market conditions to their historical performance profile, eliminating guesswork
Transparent Occurrence Counts: Displays sample sizes directly in each cell, allowing traders to judge statistical reliability themselves rather than hiding data quality issues
Fully Customizable Analysis Window: Complete control over lookback depth and forward return horizons lets traders align the tool precisely with their trading timeframe and strategy requirements
🔬How It Works
1. State Classification and Encoding
Each bar’s RSI value is evaluated and assigned to one of 7 discrete states based on threshold levels (0: <20, 1: 20-30, 2: 30-40, 3: 40-60, 4: 60-70, 5: 70-80, 6: >80)
Simultaneously, three binary conditions are evaluated: MACD line position relative to signal line, current volume relative to its moving average, and current close relative to previous close
These three binary conditions are combined into a single indicator state integer (0-7) using binary encoding, creating 8 possible indicator combinations
The RSI state and indicator state are stored together, defining one of 56 possible market condition cells in the matrix
2. Historical Data Accumulation
As each bar completes, the current state classification, closing price, and bar index are stored in rolling arrays maintained at the size specified by the lookback period
When the arrays reach capacity, the oldest data point is removed and the newest added, creating a sliding historical window
This continuous process builds a comprehensive database of past market conditions and their subsequent price movements
3. Forward Return Calculation and Statistics Update
On each bar, the indicator looks back through the stored historical data to find bars where sufficient forward bars exist to measure outcomes
For each historical occurrence, the price change from that bar to the bar N periods ahead (where N is the forward performance bars setting) is calculated as a percentage return
This percentage return is added to the cumulative return total for the specific matrix cell corresponding to that historical bar’s state classification
Occurrence counts are incremented, and wins are tallied for positive returns, building comprehensive statistics for each of the 56 cells
The Bayesian smoothing formula combines these raw statistics with prior assumptions (neutral 50% win rate) weighted by the smoothing strength parameter to produce estimated win rates that remain stable even with small samples
💡Note:
The Historical Matrix Analyzer is designed as a decision support tool, not a standalone trading system. Best results come from using it to validate discretionary trade ideas or filter systematic strategy signals. Always combine matrix insights with proper risk management, position sizing rules, and awareness of broader market context. The estimated win rate feature uses Bayesian statistics specifically to prevent false confidence from limited data, but no amount of smoothing can create reliable predictions from fundamentally insufficient sample sizes. Focus on high-confidence cells (green-colored confidence indicators) with occurrence counts well above your minimum threshold for the most actionable insights.
Fair Value Lead-Lag Model [BackQuant]Fair Value Lead-Lag Model
A cross-asset model that estimates where price "should" be relative to a chosen reference series, then tracks the deviation as a normalized oscillator. It helps you answer two questions: 1) is the asset rich or cheap vs its driver, and 2) is the driver leading or lagging price over the next N bars.
Concept in one paragraph
Many assets co-move with a macro or sector driver. Think BTC vs DXY, gold vs real yields, a stock vs its sector ETF. This tool builds a rolling fair value of the charted asset from a reference series and shows how far price is above or below that fair value in standard deviation units. You can shift the reference forward or backward to test who leads whom, then use the deviation and its bands to structure mean-reversion or trend-following ideas.
What the model does
Reference mapping : Pulls a reference symbol at a chosen timeframe, with an optional lead or lag in bars to test causality.
Fair value engine : Converts the reference into a synthetic fair value of the chart using one of four methods:
Ratio : price/ref with a rolling average ratio. Good when the relationship is proportional.
Spread : price minus ref with a rolling average spread. Good when the relationship is additive.
Z-Score : normalizes both series, aligns on standardized units, then re-projects to price space. Good when scale drifts.
Beta-Adjusted : rolling regression style. Uses covariance and variance to compute beta, then builds a fair value = mean(price) + beta * (ref − mean(ref)).
Deviation and bands : Computes a z-scored deviation of price vs fair value and plots sigma bands (±1, ±2, ±3) around the fair value line on the chart.
Correlation context : Shows rolling correlation so you can judge if deviations are meaningful or just noise when co-movement is weak.
Visuals :
Fair value line on price chart with sigma envelopes.
Deviation as a column oscillator and optional line.
Threshold shading beyond user-set upper and lower levels.
Summary table with reference, deviation, status, correlation, and method.
Why this is useful
Mean reversion framework : When correlation is healthy and deviation stretches beyond your sigma threshold, probability favors reversion toward fair value. This is classic pairs logic adapted to a driver and a target.
Trend confirmation : If price rides the fair value line and deviation stays modest while correlation is positive, it supports trend persistence. Pullbacks to negative deviation in an uptrend can be buyable.
Lead-lag discovery : Shift the reference forward by +N bars. If correlation improves, the reference tends to lead. Shift backward for the reverse. Use the best setting for planning early entries or hedges.
Regime detection : Large persistent deviations with falling correlation hint at regime change. The relationship you relied on may be breaking down, so reduce confidence or switch methods.
How to use it step by step
Pick a sensible reference : Choose a macro, index, currency, or sector driver that logically explains the asset’s moves. Example: gold with DXY, a semiconductor stock with SOXX.
Test lead-lag : Nudge Lead/Lag Periods to small positive values like +1 to +5 to see if the reference leads. If correlation improves, keep that offset. If correlation worsens, try a small negative value or zero.
Select a method :
Start with Beta-Adjusted when the relationship is approximately linear with drift.
Use Ratio if the assets usually move in proportional terms.
Use Spread when they trade around a level difference.
Use Z-Score when scales wander or volatility regimes shift.
Tune windows :
Rolling Window controls how quickly fair value adapts. Shorter equals faster but noisier.
Normalization Period controls how deviations are standardized. Longer equals stabler sigma sizing.
Correlation Length controls how co-movement is measured. Keep it near the fair value window.
Trade the edges :
Mean reversion idea : Wait for deviation beyond your Upper or Lower Threshold with positive correlation. Fade back toward fair value. Exit at the fair value line or the next inner sigma band.
Trend idea : In an uptrend, buy pullbacks when deviation dips negative but correlation remains healthy. In a downtrend, sell bounces when deviation spikes positive.
Read the table : Deviation shows how many sigmas you are from fair value. Status tells you overvalued or undervalued. Correlation color hints confidence. Method tells you the projection style used.
Reading the display
Fair value line on price chart: the model’s estimate of where price should trade given the reference, updated each bar.
Sigma bands around fair value: a quick sense of residual volatility. Reversions often target inner bands first.
Deviation oscillator : above zero means rich vs fair value, below zero means cheap. Color bins intensify with distance.
Correlation line (optional): scale is folded to match thresholds. Higher values increase trust in deviations.
Parameter tips
Start with Rolling Window 20 to 30, Normalization Period 100, Correlation Length 50.
Upper and Lower Threshold at ±2.0 are classic. Tighten to ±1.5 for more signals or widen to ±2.5 to focus on outliers.
When correlation drifts below about 0.3, treat deviations with caution. Consider switching method or reference.
If the fair value line whipsaws, increase Rolling Window or move to Beta-Adjusted which tends to be smoother.
Playbook examples
Pairs-style reversion : Asset is +2.3 sigma rich vs reference, correlation 0.65, trend flat. Short the deviation back toward fair value. Cover near the fair value line or +1 sigma.
Pro-trend pullback : Uptrend with correlation 0.7. Deviation dips to −1.2 sigma while price sits near the −1 sigma band. Buy the dip, target the fair value line, trail if the line is rising.
Lead-lag timing : Reference leads by +3 bars with improved correlation. Use reference swings as early cues to anticipate deviation turns on the target.
Caveats
The model assumes a stable relationship over the chosen windows. Structural breaks, policy shocks, and index rebalances can invalidate recent history.
Correlation is descriptive, not causal. A strong correlation does not guarantee future convergence.
Do not force trades when the reference has low liquidity or mismatched hours. Use a reference timeframe that captures real overlap.
Bottom line
This tool turns a loose cross-asset intuition into a quantified, visual fair value map. It gives you a consistent way to find rich or cheap conditions, time mean-reversion toward a statistically grounded target, and confirm or fade trends when the driver agrees.
NY 4H Wyckoff State Machine [CHE] NY 4H Wyckoff State Machine — Full (Re-Entry, Breakout, Wick, Re-Accum/Distrib, Dynamic Table) — One-Candle Wyckoff Re-Entry (OCWR)
Summary
OCWR operationalizes a one-candle session workflow: mark the first four-hour New York candle, fix its high and low as the session range when the window closes, and drive entries through a Wyckoff-style state machine on intraday bars. The script adds an ATR-scaled buffer around the range and requires multi-bar acceptance before treating breaks or re-entries as valid. Optional wick-cluster evidence, a proximity retest, and simple volume or RSI gates increase selectivity. Background tints expose regimes, shapes mark events, a dynamic table explains the current state, and hidden plots supply alert payloads. The design reduces random flips and makes state transitions auditable without higher-timeframe calls.
Origin and name
Method name: One-Candle Wyckoff Re-Entry (OCWR)
Transcript origin: The source idea is a “stupid simple one-candle scalping” routine: mark the first New York four-hour candle (commonly between one and five in the morning New York time), drop to five minutes, observe accumulation inside, wait for a manipulation move outside, then trade the re-entry back inside. Stops go beyond the excursion extreme; targets are either a fixed reward multiple or the opposite side of the range. Preference is given to several manipulation candles. This indicator codifies that workflow with explicit states, acceptance counters, buffers, and optional quality filters. Any external performance claims are not part of the code.
Motivation: Why this design?
Session levels are widely respected, yet single-bar breaches around them are noisy. OCWR separates range discovery from trade logic. It locks the range at the end of the window, applies an ATR-scaled buffer to ignore marginal oversteps, and requires acceptance over several bars for breaks and re-entries. Wick evidence and optional retest proximity help confirm that an excursion likely cleared liquidity rather than launched a trend. This yields cleaner transitions from test to commitment.
What’s different vs. standard approaches?
Baseline: Static session lines or one-shot Wyckoff tags without process control.
Architecture: Dual long and short state machines; ATR-buffered edges; multi-bar acceptance for breaks and re-entries; optional wick dominance and cluster checks; optional retest tolerance; direct and opposite breakout paths; cooldown after fires; distribution timeout; dynamic table with highlighted row.
Practical effect: Fewer single-bar head-fakes, clearer hand-offs, and on-chart explanations of the machine’s view.
Wyckoff structure by example — OCWR on five minutes
One-candle setup:
On the four-hour chart, mark the first New York candle’s high and low, then switch to five minutes. Solid lines show the fixed range; dashed lines show ATR-buffered edges.
Long path (verbal mapping):
Phase A, Stopping Action: Price stabilizes inside the range.
Phase B, Consolidation: Sustained balance while the window is closed and after the range is fixed.
Phase C, Test (Spring): Excursion below the buffered low with preference for several outside bars and dominant lower wicks, then a return inside.
Re-entry acceptance: A required run of inside bars validates the test.
Phase D, Breakout to Markup: Long signal fires; stop beyond the excursion extreme; objective is the opposite range or a fixed reward multiple.
Phase E, Trend (Markup) and Re-Accumulation: Advance continues until target, stop, confirmation back against the box, or timeout. A pause inside trend may register as re-accumulation.
Short path mirrors the above: A UTAD-style move forms above the buffered high, then re-entry leads to Markdown and possible re-distribution.
Variant map (verbal):
Accumulation after a downtrend: with Spring and Test, or without Spring; both proceed to Markup and may pause in Re-Accumulation.
Distribution after an uptrend: with UTAD and Test, or without UTAD; both proceed to Markdown and may pause in Re-Distribution.
Note: Phases A through E occur within each variant and are not separate variants.
How it works (technical)
Session window: A configurable four-hour New York window records its high and low. At window end, the bounds are fixed for the session.
ATR buffer: A margin above and below the fixed range discourages triggers from tiny oversteps.
Inside and outside: Users choose close-based or wick-based detection. Overshoot requirements are expressed verbally as a fraction of the range with an optional absolute minimum.
Manipulation tracking: The machine counts bars spent outside and records the side extreme.
Re-entry acceptance: After a return inside, a specified number of inside bars must print before acceptance.
Direct and opposite breakouts: Direct breakouts from accumulation and opposite breakouts after manipulation are supported, subject to acceptance and optional filters.
Targets and exits: Choose the opposite boundary or a fixed reward multiple. Distribution ends on target, stop, confirmation back against the range, or timeout.
Context filters (optional): Volume above a scaled SMA, RSI thresholds, and a trend SMA for simple regime context.
Diagnostics: Background tints for regimes; arrows for re-entries; triangles for breakouts; table with row highlights; hidden plots for alert values.
Central table (Wyckoff console)
The table sits top-right and explains the machine’s stance. Columns: Structure label, plain-English description, active state pair for long and short, and human phase tags. Rows: Start and range building; accumulation branch with Spring and Test as well as direct breakout; Markup and re-accumulation; distribution branch with UTAD and Test as well as direct short breakout; Markdown and re-distribution. Only the active state cell is rewritten each last bar, for example “L_ACCUM slash S_ACCUM”. Row highlighting is context-aware: accumulation, Spring or UTAD, breakout, Markup or Markdown, and re-accumulation or re-distribution checks can highlight independently so users see simultaneous conditions. The table is created once, updated only on the last bar for efficiency, and functions as a read-only console to audit why a signal fired and where the path currently sits.
Parameter Guide
Session window and time zone: First four hours of New York by default; time zone “America/New_York”.
ATR length and buffer factor: Control buffer size; larger reduces sensitivity, smaller reacts faster.
Minimum overshoot (fraction and absolute): Demand meaningful extension beyond the buffer.
Break mode: Close-based is stricter; wick-based is more reactive.
Acceptance counts: Separate counts for break, re-entry, and opposite breakout; higher values reduce noise.
Minimum bars outside: Ensures manipulation is not a single spike.
Wick detection and clusters (optional): Dominance thresholds and cluster size within a short window.
Retest required and tolerance (optional): Gate re-entry by proximity to the buffered edge.
Volume and RSI filters (optional): Simple gates on activity and momentum.
TP mode and reward multiple: Opposite range or fixed multiple.
Cooldown and distribution timeout: Rate-limit signals and prevent endless distribution.
Visualization toggles: Background phases, labels, table, and helper lines.
Reading & Interpretation
Solid lines are the fixed session bounds; dashed lines are buffers. Backgrounds tint accumulation, manipulation, and distribution. Arrows show accepted re-entries; triangles show direct or opposite breakouts. Labels can summarize entry, stop, target, and risk. The table highlights the active row and the current state pair.
Practical Workflows & Combinations
OCWR baseline: Each morning, mark the New York four-hour candle, move to five minutes, prefer multi-bar manipulation outside, then wait for a qualified re-entry inside. Stop beyond the excursion extreme. Target the opposite range for conservative management or a fixed multiple for uniform sizing.
Trend following: Favor direct breakouts with trend alignment and no contradictory wick evidence.
Quality control: When noise rises, increase acceptance, raise the buffer factor, enable retest, and require wick clusters.
Discretionary confluences: Fair-value gaps and trend lines can be added by the user; they are not computed by this script.
Behavior, Constraints & Performance
Closed-bar confirmation is recommended when you require finality; live-bar conditions can change until close. The script does not call higher-timeframe data. It uses arrays, lines, labels, boxes, and a table; maximum bars back is five thousand; table updates are last-bar only. Known limits include compressed buffers in quiet sessions, unreliable wick evidence in thin markets, and session misalignment if the platform time zone is not New York.
Sensible Defaults & Quick Tuning
Start with ATR length fourteen, buffer factor near zero point fifteen, overshoot fraction near zero point ten, acceptance counts of two, minimum outside duration three, retest required on.
Too many flips: increase acceptance, raise buffer, enable retest, and tighten wick thresholds.
Too slow: reduce acceptance, lower buffer, switch to wick-based breaks, disable retest.
Noisy wicks: increase minimum wick ratio and cluster size, or disable wick detection.
What this indicator is—and isn’t
A session-anchored visualization and signal layer that formalizes a Wyckoff-style re-entry and breakout workflow derived from a single four-hour New York candle. It is not predictive and not a complete trading system. Use with structure analysis, risk controls, and position management.
Disclaimer
The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.
Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.
By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.
Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.
Best regards and happy trading
Chervolino