200/100 vs 190/80 EMA [jarederaj]Track the 200/100 EMA cross Vs the 180/90 EMA cross. Also, see the dates when these periods start on the chart.
Cerca negli script per "track"
Consecutive Highs/LowsTrack consecutive new highs/lows outside the Donchian range. Fans of the oldschool Turtle Strategy should enjoy the visualization.
Same logic as my "Walking the Bands" script, just with Donchian breaks instead of Bollinger tags.
Altcoin PortfolioTrack your altcoin portfolio balance in Fiat currency.
Make sure to open the data window to the right of your charts, it makes everything alot easier to read at a glance.
To learn more about customizing this script to fit your portfolio, watch the video here: youtu.be
To get more cool scripts and up-to-date information about Autoview, join us in slack slack.with.pink
As per the usual, we hope this script helps with your trading venture.
Good luck, and happy trading.
Elite Display# 😎 Elite Display - Simple Chart Info with Style
**Never lose track of what you're looking at!**
A clean, fun way to display your asset name, timeframe, and daily performance directly on your chart. Created by ** ** for traders who like their charts both informative and stylish.
## 📊 **What it shows:**
- Asset name (BTCUSDT) or description (Bitcoin/TetherUS)
- Current timeframe (1H, 4H, 1D, etc.)
- Daily % change with green/red colors
**Example:** `BTCUSDT | 1H | +2.45%`
## 🎨 **Make it yours:**
- **60+ separator styles** - From classic `|` to fun emojis 🚀💎⚡
- **Mood mode** - Separators react to your performance (😄 for gains, 😢 for losses)
- **Position anywhere** - 9 spots on your chart
- **Custom styling** - Colors, fonts, sizes, bold/italic
## 🎯 **Perfect for:**
- Multi-timeframe analysis (never forget which TF you're on!)
- Taking clean screenshots for social media
- Avoiding "wait, what symbol is this?" moments
- Adding a bit of personality to your workspace
## ⚙️ **Super simple setup:**
1. Add to chart
2. Pick what to show (asset/timeframe/both)
3. Choose your style (classic, fun, or reactive mood)
4. Position it wherever you want
5. Done!
**It's just chart info... but way more fun!** 😊
*Works on all markets: Stocks, Crypto, Forex, Commodities*# 📊 TradingHUD - Your Smart Chart Companion
**Transform your charts with the ultimate context display!** Never lose track of your symbol, timeframe, and performance again. This highly customizable indicator brings personality and clarity to your trading workspace.
## 🚀 **Key Features:**
✅ **5 Display Modes:**
- Asset Name (ticker only)
- Full Description (complete name)
- Both combined
- Timeframe Only
- Daily Variation Only
✅ **60+ Separator Styles in 3 Categories:**
- 🎨 **Classic** (15): Professional symbols (|, •, →, ★, etc.)
- 🎉 **Fun** (20): Colorful objects (🚀, 💎, ⚡, 🎯, 💰, etc.)
- 🎭 **Mood** (40+): Reactive yellow faces!
- 😄 **Happy** (21): 😀😊🥰😎🥳 (for green gains)
- 😢 **Sad** (23): 😢😭🥺😞😩 (for red losses)
✅ **Intelligent Variation Display:**
- Daily % change with smart color coding
- Green/red performance tracking
- Only appears on relevant timeframes (intraday + daily)
- Automatically hidden on weekly/monthly
✅ **Ultimate Customization:**
- 9 positioning options anywhere on chart
- Font families: Default or Monospace
- Bold/italic text formatting
- Custom colors and sizes
- Flexible element ordering
## 🎭 **Mood Mode Magic:**
Watch your separators celebrate wins with 😄🤑🚀 or empathize with losses using 😢😭💸. Toggle this emotional feature on/off anytime!
## 💡 **Perfect For:**
- Multi-timeframe analysis
- Screenshot documentation with context
- Avoiding symbol confusion
- Real-time performance tracking
- Adding personality to professional charts
- Social media trading posts
## ⚙️ **Quick Setup:**
1. Add TradingHUD to your chart
2. Select display mode (Asset/Description/Both/etc.)
3. Choose separator style (Classic/Fun/Mood)
4. Position anywhere you want
5. Customize colors, fonts, and formatting
6. Trade with confidence and style!
## 🎯 **Live Examples:**
- **Classic**: `BTCUSDT | 1H | +2.45%`
- **Fun**: `AAPL 🚀 4H 🚀 -1.23%`
- **Happy Mood**: `Gold 😄 1D 😄 +3.67%`
- **Sad Mood**: `BTC 😢 15min 😢 -5.12%`
**Professional meets personality. Context meets creativity. This is TradingHUD.** 📈✨
*Compatible with all markets: Stocks, Crypto, Forex, Commodities, Indices*
Delta Weighted Momentum Oscillator @MaxMaserati DELTA WEIGHTED MOMENTUM OSCILLATOR
This advanced indicator analyzes the battle between buyers and sellers by measuring volume distribution within each candle. Unlike traditional volume indicators, it reveals WHO is winning the fight - buyers or sellers - and shows you when smart money is accumulating or distributing.
📊 KEY FEATURES:
- Normalized 0-100 scale (works on any timeframe/instrument)
- Real-time delta pressure detection
- Cumulative session flow tracking
- Volume-weighted signal confirmation
- Smart money flow detection
- Multi-signal system (triangles, circles, diamonds)
- Customizable signal sizes and colors
- Professional info panel
🎯 TRADING SIGNALS EXPLAINED:
🔺 TRIANGLES (Main Entry Signals):
- Green Triangle UP: Buying pressure takes control (above 50 line)
- Red Triangle DOWN: Selling pressure takes control (below 50 line)
- Best used with volume confirmation
⚫ CIRCLES (Zone Confirmations):
- Green Circle: Strong bullish zone entry (above 70)
- Red Circle: Strong bearish zone entry (below 30)
- Use for position additions or late entries
💎 DIAMONDS (Extreme Warnings):
- Green Diamond: Extreme bullish levels (above 85) - Consider profit-taking
- Red Diamond: Extreme bearish levels (below 15) - Consider profit-taking
🎨 VISUAL ELEMENTS:
📏 KEY LINES:
- Black Dotted Line (50): The decision zone - above = bullish control, below = bearish control
- Main Delta Line: Real-time buying vs selling pressure (thick line)
- Cumulative Flow Line: Session's net money flow direction (thin line)
- Volume Area: Bottom colored area showing participation levels
🎨 BACKGROUND ZONES:
- Light Green: Bullish zones (70-85)
- Light Red: Bearish zones (15-30)
- Stronger colors: Extreme zones (above 85 / below 15)
📋 INFO PANEL:
- Delta: Current pressure reading (0-100)
- Cumulative: Session's total flow direction
- Volume: Current participation level
- Trend: Overall market sentiment
- Signal: Current recommended action
⚙️ CUSTOMIZATION OPTIONS:
- Session length (for cumulative tracking)
- Lookback period (for normalization)
- Delta smoothing (noise reduction)
- Zone thresholds (bullish/bearish/extreme levels)
- Signal sizes (tiny/small/normal)
- All colors and visual elements
- Show/hide any component
⚠️ REVERSAL SIGNALS:
1. Watch for diamonds in extreme zones
2. Look for divergence between delta and price
3. Wait for opposite triangle for confirmation
4. Manage risk carefully in extreme zones
💡 PRO TIPS:
- Don't trade triangles alone - wait for circle confirmation
- Higher volume = stronger signals
- The 50 line is your key decision point
- Diamonds = caution, not new entries
- Cumulative line shows session bias
- Works best when delta aligns with price action
⚡ BEST TIMEFRAMES:
- 1-5 minutes: Scalping and day trading
- 15-60 minutes: Swing trading
- Daily: Position trading and trend analysis
🎯 UNIQUE ADVANTAGES:
- Normalized scale works on any market
- Combines delta, volume, and flow analysis
- Clear visual hierarchy
- Professional-grade normalization
- Real-time smart money detection
- Session-based cumulative tracking
This indicator is perfect for traders who want to understand the real market sentiment beyond just price action. See exactly when institutions are buying or selling, and trade with the smart money flow!
Delta OrderFlow Sweep & Absorption Toolkit @MaxMaserati 2.0Delta OrderFlow Sweep & Absorption Toolkit @MaxMaserati 2.0
This is a professional-grade smart money order flow analysis tool that reveals smart money activity, volume absorption patterns, and liquidity sweeps in real-time. It combines advanced market microstructure concepts into one comprehensive toolkit that shows you where and how institutions are trading.
A CLEAR VISUALIZATION OF THE INDICATOR CAPACITY
🔥 Core Features Explained
1. Delta Order Flow Analysis
Tracks cumulative buying vs selling pressure (Delta)
🔥BUY/🔥SELL labels show aggressive order flow imbalances
Real-time market sentiment based on actual volume flow
Session delta tracking with automatic resets
2. Institutional Detection
🏦↑/🏦↓ labels identify large block trades and smart money activity
Automatic threshold detection based on volume patterns
Smart money flow tracking with institutional bias indicators
Institutional buyers getting in
3. Advanced Sweep Detection
SWEEP↑/SWEEP↓ labels detect stop-loss hunts with volume confirmation
Wick rejection analysis ensures proper sweep identification
Institutional reaction confirmation - shows when opposite side takes control
4. Volume Absorption Analysis
ABSORB↑/ABSORB↓ shows successful volume breakthroughs
H↑BuV Fail/H↑BeV Fail shows institutional volume failures (reversal signals)
Context-aware analysis based on recent institutional activity
Bullish Absorption scenario
Bearish Absorption scenario
5. Point of Control (POC) Levels
Dynamic support/resistance based on executed volume
POC SUP (Green) / POC RES (Purple)
POC Support Broken
6. Net Delta Bubbles
Visual representation of net buying/selling bias
Positive Delta (Green) = Bullish bias bubbles below candles
Negative Delta (Red) = Bearish bias bubbles above candles
6 positioning methods with full customization
The Net Delta Bubbles allow to see clearer, the highest reversal/continuity areas
7. Smart Alert System
Large order flow imbalances
Institutional activity detection
Stop sweep confirmations
Volume absorption patterns
📊 How to Read the Signals
🔥BUY (below candles) = Aggressive institutional buying
🔥SELL (above candles) = Aggressive institutional selling
Threshold: Customizable imbalance percentage (default 75%)
🏦 Institutional Labels:
🏦↑ (below candles) = Large institutional buying detected
🏦↓ (above candles) = Large institutional selling detected
Volume: Based on block trade size detection
⚡ Sweep Labels:
SWEEP↑ (below candles) = Stop hunt below, expect reversal UP
SWEEP↓ (above candles) = Stop hunt above, expect reversal DOWN
Confirmation: Requires wick rejection + volume confirmation
🎯 Absorption Labels:
ABSORB↑ = True bullish breakthrough above institutional levels
ABSORB↓ = True bearish breakdown below institutional levels
H↑BuV Fail (Orange) = Bullish volume failed = Bearish signal
H↑BeV Fail (Blue) = Bearish volume failed = Bullish signal
💡 Trading Strategies
🟢 Bullish Setups:
🔥BUY + 🏦↑ = Strong institutional buying confirmation
SWEEP↓ + High volume = Stop hunt below, enter long on reversal
H↑BeV Fail = Bearish volume failed, bullish reversal signal
POC Support holding + positive delta = Bounce play
ABSORB↑ = Successful break above resistance
🔴 Bearish Setups:
🔥SELL + 🏦↓ = Strong institutional selling confirmation
SWEEP↑ + High volume = Stop hunt above, enter short on reversal
H↑BuV Fail = Bullish volume failed, bearish reversal signal
POC Resistance holding + negative delta = Rejection play
ABSORB↓ = Successful break below support
⚡ High-Probability Entries:
Multiple confirmations on same candle/area
Volume spikes with directional bias
Failed institutional attempts (reversal plays)
POC level interactions with delta confirmation
📱 Best Practices
🎯 Timeframe Usage:
1-5 minutes: Scalping with institutional confirmation
15-30 minutes: Day trading with sweep detection
1-4 hours: Swing trading with POC levels
Daily: Position trading with major delta shifts
🔧 Optimization Tips:
Start with defaults and adjust sensitivity based on your instrument
Use multiple confirmations - don't trade single signals
Watch volume bubbles for additional bias confirmation
Enable alerts for key institutional activity
Combine with price action for best results
⚠️ Important Notes:
No repainting - all signals are final when candle closes
Volume-based - works best on liquid instruments
Context matters - consider overall market conditions
Risk management - use proper position sizing
Enigma UnlockedENIGMA Indicator: A Comprehensive Market Bias & Success Tracker
The ENIGMA Indicator is a powerful tool designed for traders who aim to identify market bias, track price movements, and evaluate trade performance using multiple timeframes. It combines multiple indicators and advanced logic to provide real-time insights into market trends, helping traders make more informed decisions.
Key Features
1. Multi-Timeframe Bias Calculation:
The ENIGMA Indicator tracks the market bias across multiple timeframes—Daily (D), 4-Hour (H4), 1-Hour (H1), 30-Minute (30M), 15-Minute (15M), 5-Minute (5M), and 1-Minute (1M).
How the Bias is Created:
The Bias is a key feature of the ENIGMA Indicator and is determined by comparing the current price with previous price levels for each timeframe.
- Bullish Bias (1): The market is considered **bullish** if the **current closing price** is higher than the **previous timeframe’s high**. This suggests that the market is trending upwards, and buyers are in control.
- Bearish Bias (-1): The market is considered **bearish** if the **current closing price** is lower than the **previous timeframe’s low**. This suggests that the market is trending downwards, and sellers are in control.
- Neutral Bias (0): The market is considered **neutral** if the price is between the **previous high** and **previous low**, indicating indecision or a range-bound market.
This bias calculation is performed independently for each timeframe. The **Bias** for each timeframe is then displayed in the **Bias Table** on your chart, providing a clear view of market direction across multiple timeframes.
2. **Customizable Table Display:**
- The indicator provides a table that displays the bias for each selected timeframe, clearly marking whether the market is **Bullish**, **Bearish**, or **Neutral**.
- Users can choose where to place the table on the chart: top-left, top-right, bottom-left, bottom-right, or center positions, allowing for easy and personalized chart management.
3. **Win/Loss Tracker:**
- The table also tracks the **success rate** of **buy** and **sell** trades based on price retests of key bias levels.
- For each period (Day, Week, Month), it tracks how often the price has moved in the direction of the initial bias, counting **Buy Wins**, **Sell Wins**, **Buy Losses**, and **Sell Losses**.
- This helps traders assess the effectiveness of the market bias over time and adjust their strategies accordingly.
#### **How the Success Calculation Determines the Success Rate:**
The **Success Calculation** is designed to track how often the price follows the direction of the market bias. It does this by evaluating how the price retests key levels associated with the identified market bias:
1. **Buy Success Calculation**:
- The success of a **Buy Trade** is determined when the price breaks above the **previous high** after a **bullish bias** has been identified.
- If the price continues to move higher (i.e., makes a new high) after breaking the previous high, the **buy trade is considered successful**.
- The indicator tracks how many times this condition is met and counts it as a **Buy Win**.
2. **Sell Success Calculation**:
- The success of a **Sell Trade** is determined when the price breaks below the **previous low** after a **bearish bias** has been identified.
- If the price continues to move lower (i.e., makes a new low) after breaking the previous low, the **sell trade is considered successful**.
- The indicator tracks how many times this condition is met and counts it as a **Sell Win**.
3. **Failure Calculations**:
- If the price does not move as expected (i.e., it does not continue in the direction of the identified bias), the trade is considered a **loss** and is tracked as **Buy Loss** or **Sell Loss**, depending on whether it was a bullish or bearish trade.
The ENIGMA Indicator keeps a running tally of **Buy Wins**, **Sell Wins**, **Buy Losses**, and **Sell Losses** over a set period (which can be customized to Days, Weeks, or Months). These statistics are updated dynamically in the **Bias Table**, allowing you to track your success rate in real-time and gain insights into the effectiveness of the market bias.
#### **Customizable Period Tracking:**
- The ENIGMA Indicator allows you to set custom tracking periods (e.g., 30 days, 2 weeks, etc.). The performance metrics reset after each tracking period, helping you monitor your success in different market conditions.
5. **Interactive Settings:**
- **Lookback Period**: Define how many bars the indicator should consider for bias calculations.
- **Success Tracking**: Set the number of candles to track for calculating the win/loss performance.
- **Time Threshold**: Set a time threshold to help define the period during which price retests are considered valid.
- **Info Tooltip**: You can enable the information tool in the settings to view detailed explanations of how wins and losses are calculated, ensuring you understand how the indicator works and how the results are derived.
#### **How to Use the ENIGMA Indicator:**
1. **Install the Indicator**:
- Add the ENIGMA Indicator to your chart. It will automatically calculate and display the bias for multiple timeframes.
2. **Interpret the Bias Table**:
- The bias table will show whether the market is **Bullish**, **Bearish**, or **Neutral** across different timeframes.
- Look for alignment between the timeframes—when multiple timeframes show the same bias, it may indicate a stronger trend.
3. **Use the Win/Loss Tracker**:
- Track how well your trades align with the bias using the **Win/Loss Tracker**. This helps you refine your strategy by understanding which timeframes and biases lead to higher success rates.
- For example, if you see a high number of **Buy Wins** and a low number of **Sell Wins**, you may decide to focus more on buying during bullish trends and avoid selling during bearish retracements.
4. **Track Your Period Performance**:
- The indicator will automatically track your performance over the set period (Days, Weeks, Months). Use this data to adjust your approach and evaluate the effectiveness of your trading strategy.
5. **Position the Table**:
- Customize the placement of the table on your chart based on your preferences. You can choose from options like **Top Left**, **Top Right**, **Bottom Left**, **Bottom Right**, or **Center** to keep the chart uncluttered.
6. **Adjust Settings**:
- Modify the indicator settings according to your trading style. You can adjust the **Lookback Period**, **Number of Candles to Track**, and **Time Threshold** to match the pace of your trading.
7. **Use the Info Tooltip**:
- Enable the **Info Tool** in the settings to understand how the Buy/Sell Wins and Losses are calculated. The tooltip provides a breakdown of how the indicator tracks price movements and calculates the success rate.
**Conclusion:**
The **ENIGMA Indicator** is designed to help traders make informed decisions by providing a clear view of the market bias and performance data. With the ability to track bias across multiple timeframes and evaluate your trading success, it can be a powerful tool for refining your trading strategies.
Whether you're looking to focus on a single timeframe or analyze multiple timeframes for a stronger bias, the ENIGMA Indicator adapts to your needs, providing both real-time market insights and performance feedback.
Smart Money Volume Execution Footprint @MaxMaserati 2.0 Smart Money Volume Execution Footprint @MaxMaserati 2.0
Volume and Price Execution Tracker · Volume Delta · VWAP · POC · DOM Simulation
Overview
This volume and price tool high grade tool reveals **where** smart money is actually executing within each candle — not just how much volume traded, but the **exact price levels** where large buy/sell orders hit the tape.
By simulating Depth of Market (DOM) logic, it breaks each candle into price levels (default: 8–20) and reconstructs intra-candle volume pressure to identify:
• Institutional execution zones
• Buy vs Sell dominance
• Volume-weighted positioning
• Smart money flow bias (bullish / bearish / neutral)
Think of it as a powerful X-ray footprint to spot real-time volume/price behavior.
Core Features
Execution Dots (Smart Money Signatures)
• Plots dots at key institutional execution prices
• Color-coded: 🟢 Green = dominant buy volume · 🔴 Red = dominant sell volume
• Dot size = Volume Intensity (relative to average):
– tiny < 1.0x avg
– small 1.0x–1.5x
– normal 1.5x–2.5x
– large 2.5x–4.0x
– huge > 4.0x (massive positioning)
Volume Modes (Buy/Sell Breakdown)
• Total Volume Mode: Combined buy + sell volume at each price level
• Volume Delta Mode: Net buy/sell pressure (buy − sell)
Dot Placement Modes
• Volume POC: Dot at level with highest volume (Point of Control)
• VWAP: Dot at intra-candle volume-weighted average price
• Highest Volume Level: Similar to POC, simplified for fast bias detection
Smart Money Bias Detection
Real-time consensus calculation based on buy/sell volume ratio:
🟢 Bullish Consensus (>60% Buy Volume): Smart money buying → Long bias
🔴 Bearish Consensus (<40% Buy Volume): Smart money selling → Short bias
⚪ Neutral Market (40–60%): Market in balance → Wait for breakout
This logic powers the volume execution table, showing institutional sentiment per candle.
Dot Placement Example (How It Works)
Let’s say you break a candle into 10 price levels:
• Volume POC Mode → Dot at \$4,297.50, where volume was highest
• VWAP Mode → Dot around \$4,275, the volume-weighted average
• Volume Delta Mode → Dot where net buying/selling pressure peaked
Dot sizes based on volume intensity:
Level 1 (400K): size.huge — heavy institutional execution
Level 10 (300K): size.normal — passive accumulation
Level 5 (250K): size.normal — potential battle zone
🔗 Optional Visual Enhancements
• Zigzag Lines: Connects execution dots to highlight flow direction
• Labels: Toggle to show volume and/or execution price directly on dots
• Execution Table: Real-time snapshot of volume ratio, delta, and institutional bias
Option to see the volume and/or exact Price level
Ideal Use Cases
Institutional Flow Strategy
1. Look for large dots (size.large or size.huge)
2. Confirm direction with bias table (bullish or bearish consensus)
3. Align entries with institutional execution zones
4. Use retests of large dot prices as entries or exits
Option to only see huge buying and selling area to solely focus on them for retest
Volume Divergence Signals
• Price making new highs, but dot size shrinking → Weak breakout
• Price making new lows, but weak dot volume → Potential bounce
• Huge dot + rejection wick → Institutional defense zone
Configurable Settings
• Dot Placement: VWAP · POC · Delta
• Volume Mode: Total vs Delta
• Price Granularity: 5 to 50 levels per candle
• Dot Labels: Volume / Price
• Table Size, Position, and Color Themes
Important Notes
• Best used on high-volume markets (futures, indices, major FX pairs)
• Ideal timeframe: 1m–15m for precision, 1h–4h for position setups
• Integrates well with VWAP, session levels, or structure-based trading
Session Overlaps & KZ's @MaxMaseratiSession Overlap & KZ's @MaxMaserati - Indicator Explanation
This comprehensive trading session indicator specializes in identifying critical market overlap periods and key session levels with two main operating modes: Normal Sessions and ICT KZ's
Dual Session Modes:
- Normal Sessions: Extended timeframes (Asia 9PM-6AM, London 3AM-12PM, NY AM 8AM-5PM, NY PM 1-7PM)
- ICT Killzones: Focused timeframes (Asia 6-8PM, London 2-5AM, NY AM 9:30-11AM, NY PM 1:30-4PM)
Primary Focus - Market Overlap Sessions:
- Asian + London Overlap (3-6AM ET): The most volatile early morning period when Asian and London markets intersect, creating significant liquidity and price movement opportunities.
- London + NY Overlap (8AM-12PM ET): The highest volume trading window of the day when London and New York markets are simultaneously active, offering maximum institutional activity and trend continuation.
- London Solo (6-8AM ET): Pure London trading period after Asian close but before NY open, often used for trend establishment and key level testing.
- NY Solo (12-5PM ET): Isolated New York session after London close, typically showing strong directional moves and institutional positioning.
- NY AM + PM Overlap (1:30-4PM ET): Critical afternoon overlap period when morning and afternoon NY sessions intersect, often marking significant reversal or continuation points.
Session Level Analysis:
Tracks High, Low, and Midpoint levels for each active session and overlap period
Smart line extension that continues levels until price interaction
Visual session boxes with customizable transparency
Show Only Overlaps mode to focus purely on market intersection periods
Critical Time Markers:
9:30 AM: NY AM Open (green dot)
5:00 AM: MMM Foundational time for MMM trading strategies (blue dot)
1:30 PM: NY PM Open (orange dot)
Additional Features:
Previous Day High/Low (PDH/PDL) levels
Multi-timezone support
Session limit control (last 3 sets by default)
Optimized for 15-minute and lower timeframes
Full customization of colors, labels, and styles
This indicator is essential for overlap-based trading strategies, providing clear visual identification of high-probability windows when multiple markets create enhanced liquidity and institutional activity.
FVG-Bully BearsFVG-Bully Bears Indicator
The FVG-Bully Bears indicator is a powerful tool designed to identify Fair Value Gaps (FVGs) on your TradingView charts. FVGs are price gaps that occur when the market moves sharply, leaving areas where little to no trading activity took place. These gaps often act as key support or resistance zones, making them valuable for traders looking to spot potential reversal or continuation points.
This indicator highlights Bullish FVGs (potential support zones) and Bearish FVGs (potential resistance zones) with customizable boxes and labels, helping you visualize these critical price levels with ease.
Features
Bullish and Bearish FVGs: Detects gaps where price has left untested areas, marking bullish (green) and bearish (red) FVGs.
Customizable Display: Choose to show or hide bullish/bearish FVGs, adjust colors, and control box visibility.
FVG Labels: Optional labels on each FVG box to clearly identify bullish or bearish gaps, with adjustable text size.
Delete Filled FVGs: Automatically removes FVGs once price revisits and fills the gap, keeping your chart clean.
Box Extension: Extend FVG boxes into the future (up to 100 bars) to track unfilled gaps over time.
Performance Optimization: Limits the number of displayed FVG boxes (default: 50) to ensure smooth chart performance.
How It Works
Bullish FVG: Identified when the high of a candle two bars ago is lower than the low of the current candle, indicating a sharp upward move.
Bearish FVG: Identified when the low of a candle two bars ago is higher than the high of the current candle, indicating a sharp downward move.
FVGs are drawn as colored boxes (green for bullish, red for bearish) and can include labels for easy identification.
If enabled, filled FVGs (where price revisits the gap) are deleted to reduce chart clutter.
Settings
FVG Settings
Show Bullish FVGs: Enable/disable bullish FVG boxes (default: enabled).
Show Bearish FVGs: Enable/disable bearish FVG boxes (default: enabled).
Bullish FVG Color: Customize the color and transparency of bullish FVG boxes (default: light green).
Bearish FVG Color: Customize the color and transparency of bearish FVG boxes (default: light red).
Max FVG Boxes: Set the maximum number of FVG boxes displayed (default: 50, range: 1–500).
Extend FVG Boxes (Bars): Extend FVG boxes into the future by a specified number of bars (default: 8, range: 0–100).
Show FVG Labels: Enable/disable text labels on FVG boxes (default: enabled).
Label Size: Choose the size of FVG labels (options: Tiny, Small, Normal, Large, Huge; default: Small).
Delete Filled FVGs: Automatically remove FVGs when price fills the gap (default: enabled).
How to Use
Add the FVG-Bully Bears indicator to your TradingView chart.
Customize the settings to match your trading style (e.g., adjust colors, toggle labels, or change box extensions).
Watch for green (bullish) and red (bearish) FVG boxes:
Bullish FVGs: Potential support zones where price may bounce or consolidate.
Bearish FVGs: Potential resistance zones where price may reverse or stall.
Use FVGs in combination with other indicators (e.g., support/resistance, trendlines) for better trade decisions.
If “Delete Filled FVGs” is enabled, filled gaps will disappear, keeping your chart focused on active FVGs.
Ideal For
Swing Traders: Identify key price zones for entries or exits.
Day Traders: Spot intraday support/resistance levels created by rapid price moves.
Price Action Traders: Use FVGs to confirm market structure and potential reversal points.
Notes
For best performance, keep “Max FVG Boxes” at a reasonable value (e.g., 50) to avoid chart lag.
FVGs are most effective on lower timeframes (e.g., 5m, 15m, 1H) but can be used on any timeframe.
Combine with other tools like volume or trend indicators for a complete trading strategy.
Enjoy trading with FVG-Bully Bears and take advantage of Fair Valu
TradeChartist Spotter ™TradeChartist Spotter is a extremely well designed Trader's toolkit that packs a range of trading indicators like MACD, RSI, MA/MA-Crosses and Price-Volume Trend Oscillator, along with visual trade spotting tools like Symbol Tracker, MACD Trend Shadow plot and Coloured Bars, including a handy information Dashboard.
===================================================================================================================
™TradeChartist Spotter Features:
1. MACD
MACD is an essential indicator for any trader to track trend strength and momentum of asset prices. Spotter offers 3 MACD options - SMA, EMA and Zero-Lag EMA . Since MACD is based on moving averages, it is inherently a lagging indicator and may not work well when there is no trend strength or when the market is choppy. It is for this reason Spotter offers the option of Overall Trend Shadow and also the option to display Zero-Lag Trend Shadow on normal MACD based on SMA or EMA. This is based on the average of MACD and Signal plots.
Spotter's default MACD settings are 13/34/13, but this can be changed to the classic settings of 12/26/9 and the user can enable or disable the various elements of the MACD based on their preference.
The Dashboard on the MACD Spotter offers information on the symbol tracked, settings used and also the close price of the asset. This is really useful especially when tracking a different symbol than the current price chart symbol. Note that the actual MACD plot also will be of the symbol tracked if it is not the same as price chart symbol.
Using Zero-Lag Trend Shadow on normal SMA/EMA MACD histogram helps spot trend changes early. It is recommended to test different MACD settings on asset traded to suit trading style and frequency.
If MACD Histogram is disabled to see the Overall Trend better, make sure to switch back on as it should not be confused with the main MACD histogram which tracks the distance between the MACD and Signal plots.
2. RSI
RSI is the classic technical indicator that helps track the price magnitude and velocity of the asset's price movement. It helps spot Oversold and Overbought areas easily as it oscillates between 0 and 100, even though values below 10 and values above 90 are almost never seen. By using a upper band and a lower band plot, it is possible to track the strength of the up or down move.
Spotter's default RSI settings are ohlc4/14/5. EMA smoothing of 5 is used to eliminate the noise, but these can be changed to suit user's preference. The default Upper Band is 60 and Lower Band is 40 in the settings, as price moves above 60 RSI tend to be bullish and price moves below 40 tend to be bearish. This can be changed to 70/30 or 80/20 etc. based on how RSI is being used by the user.
RSI strength can also be visualised on the price bars using Spotter's Coloured Bars. The bar colours can be inverted to help traders see the price action differently.
RSI Dashboard also helps track another symbol, it's RSI value and close price to help the user track another symbol on the same chart. Note that the actual RSI plot also will be of the symbol tracked if it is not the same as price chart symbol.
3. MA/MA-Crosses
Two Moving averages (SMA, EMA or Zero-Lag EMA) can be plotted with MA Crosses using the MA/MA-Crosses Spotter.
The MACD input of Fast MA Length and Slow MA Length is used to plot the MA's. To plot just one MA, same value can be entered in both MA length boxes in the settings.
The plots can be merged with the main price chart by using Move Pane Above and by merging the scales into one.
The Dashboard also helps track another symbol, it's MA plots and close price to help the user track another symbol on the same chart. Note that the actual MA plots also will be of the symbol tracked if it is not the same as price chart symbol.
4. Price-Volume Trend Oscillator
Spotter converts the Price Volume Trend (PVT) into an Oscillator, as it helps spot divergences and makes it easy to plot PVT strength as coloured bars on main price chart.
No user input required for this Oscillator plot. Note: Some Symbols don't have volume information and hence PVT Oscillator will not work on them.
PVT Oscillator Dashboard displays current bar volume (if available) along with the close price. Similar to other plots in the Spotter, the Oscillator is of the symbol tracked if its not the same as price chart symbol.
5. Useful Extras
Coloured Bars - Paints price bars with strength and intensity based on indicator used. Bar Colours can be inverted by enabling Invert Bar Colors option from Spotter settings.
Five Colour Themes - Classic, Acute Classic, Effulgence, Firefly and Hallucination
Background colour - Same as bar colour strength, but painted subtly in the indicator background.
===================================================================================================================
Note:
Alerts can be created using the name of the plot under Alert Condition for Spotter - ™TradeChartist crossing above/below etc based on the type of alert the user wants to get.
The indicator does not repaint. Alerts may display potential repaint warning, but this is because the code uses bar index for the Dashboard. For confidence in the indicator, it can be tested using bar replay to make sure the real-time and bar replay trade entries and plots stay on the same bar/timestamp.
™TradeChartist Spotter can be connected to ™TradeChartist Plug and Trade (Premium Script - not free) to generate Trade Entries, Targets, Sop Loss plots etc and to create all types of alerts. Example chart below using LINK-USDT.
===================================================================================================================
Example Charts
1. BTC-USDT 1 hr chart showing MACD with classic settings 12/26/9 on top pane with normal Overall Trend Shadow and the bottom pane with exact same settings with Zero-Lag Overall Trend Shadow.
2. XAU-USD 4 hr chart showing MACD (13/55/34) using Zero-Lag EMA.
3.ADA-USDT 1 hr chart with Price-Volume Trend Oscillator - Useful for confirming divergences and trade decisions based on volume.
4. SPX 15m chart with RSI (ohlc4,14,5) in bottom pane and 5/34 MA cross Spotter on Price Chart with Dashboard.
5. GBP-USD 1 hr chart with Spotter tracking MACD (13/89/34) of DXY (Different Symbol from GBP-USD on chart)
===================================================================================================================
Best Practice: Test with different settings first using Paper Trades before trading with real money
This is a free to use indicator.
===================================================================================================================
Quantum Reversal Engine [ApexLegion]Quantum Reversal Engine
STRATEGY OVERVIEW
This strategy is constructed using 5 custom analytical filters that analyze different market dimensions - trend structure, momentum expansion, volume confirmation, price action patterns, and reversal detection - with results processed through a multi-component scoring calculation that determines signal generation and position management decisions.
Why These Custom Filters Were Independently Developed:
This strategy employs five custom-developed analytical filters:
1. Apex Momentum Core (AMC) - Custom oscillator with volatility-scaled deviation calculation
Standard oscillators lag momentum shifts by 2-3 bars. Custom calculation designed for momentum analysis
2. Apex Wick Trap (AWT) - Wick dominance analysis for trap detection
Existing wick analysis tools don't quantify trap conditions. Uses specific ratios for wick dominance detection
3. Apex Volume Pulse (AVP) - Volume surge validation with participation confirmation
Volume indicators typically use simple averages. Uses surge multipliers with participation validation
4. Apex TrendGuard (ATG) - Angle-based trend detection with volatility band integration
EMA slope calculations often produce false signals. Uses angle analysis with volatility bands for confirmation
5. Quantum Composite Filter (QCF) - Multi-component scoring and signal generation system
Composite scoring designed to filter noise by requiring multiple confirmations before signal activation.
Each filter represents mathematical calculations designed to address specific analytical requirements.
Framework Operation: The strategy functions as a scoring framework where each filter contributes weighted points based on market conditions. Entry signals are generated when minimum threshold scores are met. Exit management operates through a three-tier system with continued signal strength evaluation determining position holds versus closures at each TP level.
Integration Challenge: The core difficulty was creating a scoring system where five independent filters could work together without generating conflicting signals. This required backtesting to determine effective weight distributions.
Custom Filter Development:
Each of the five filters represents analytical approaches developed through testing and validation:
Integration Validation: Each filter underwent individual testing before integration. The composite scoring system required validation to verify that filters complement rather than conflict with each other, resulting in a cohesive analytical framework that was tested during the development period.
These filters represent custom-developed components created specifically for this strategy, with each component addressing different analytical requirements through testing and parameter adjustment.
Programming Features:
Multi-timeframe data handling with backup systems
Performance optimization techniques
Error handling for live trading scenarios
Parameter adaptation based on market conditions
Strategy Features:
Uses multi-filter confirmation approach
Adapts position holding based on continued signal strength
Includes analysis tools for trade review and optimization
Ongoing Development: The strategy was developed through testing and validation processes during the creation period.
COMPONENT EXPLANATION
EMA System
Uses 8 exponential moving averages (7, 14, 21, 30, 50, 90, 120, 200 periods) for trend identification. Primary signals come from 8/21 EMA crossovers, while longer EMAs provide structural context. EMA 1-4 determine short-term structure, EMA 5-8 provide long-term trend confirmation.
Apex Momentum Core (AMC)
Built custom oscillator mathematics after testing dozens of momentum calculation methods. Final algorithm uses price deviation from EMA baseline with volatility scaling to reduce lag while maintaining accuracy across different market conditions.
Custom momentum oscillator using price deviation from EMA baseline:
apxCI = 100 * (source - emaBase) / (sensitivity * sqrt(deviation + 1))
fastLine = EMA(apxCI, smoothing)
signalLine = SMA(fastLine, 4)
Signals generate when fastLine crosses signalLine at +50/-50 thresholds.
This identifies momentum expansion before traditional oscillators.
Apex Volume Pulse (AVP)
Created volume surge analysis that goes beyond simple averages. Extensive testing determined 1.3x multiplier with participation validation provides reliable confirmation while filtering false volume spikes.
Compares current volume to 21-period moving average.
Requires 1.3x average volume for signal confirmation. This filters out low-volume moves during quiet periods and confirms breakouts with actual participation.
Apex Wick Trap (AWT)
Developed proprietary wick trap detection through analysis of failed breakout patterns. Tested various ratio combinations before settling on 60% wick dominance + 20% body limit as effective trap identification parameters.
Analyzes candle structure to identify failed breakouts:
candleRange = math.max(high - low, 0.00001)
candleBody = math.abs(close - open)
bodyRatio = candleBody / candleRange
upperWick = high - math.max(open, close)
lowerWick = math.min(open, close) - low
upperWickRatio = upperWick / candleRange
lowerWickRatio = lowerWick / candleRange
trapWickLong = showAWT and lowerWickRatio > minWickDom and bodyRatio < bodyToRangeLimit and close > open
trapWickShort = showAWT and upperWickRatio > minWickDom and bodyRatio < bodyToRangeLimit and close < open This catches reversals after fake breakouts.
Apex TrendGuard (ATG)
Built angle-based trend detection after standard EMA crossovers proved insufficient. Combined slope analysis with volatility bands through iterative testing to eliminate false trend signals.
EMA slope analysis with volatility bands:
Fast EMA (21) vs Slow EMA (55) for trend direction
Angle calculation: atan(fast - slow) * 180 / π
ATR bands (1.75x multiplier) for breakout confirmation
Minimum 25° angle for strong trend classification
Core Algorithm Framework
1. Composite Signal Generation
calculateCompositeSignals() =>
// Component Conditions
structSignalLong = trapWickLong
structSignalShort = trapWickShort
momentumLong = amcBuySignal
momentumShort = amcSellSignal
volumeSpike = volume > volAvg_AVP * volMult_AVP
priceStrength_Long = close > open and close > close
priceStrength_Short = close < open and close < close
rsiMfiComboValue = (ta.rsi(close, 14) + ta.mfi(close, 14)) / 2
reversalTrigger_Long = ta.crossover(rsiMfiComboValue, 50)
reversalTrigger_Short = ta.crossunder(rsiMfiComboValue, 50)
isEMACrossUp = ta.crossover(emaFast_ATG, emaSlow_ATG)
isEMACrossDown = ta.crossunder(emaFast_ATG, emaSlow_ATG)
// Enhanced Composite Score Calculation
scoreBuy = 0.0
scoreBuy += structSignalLong ? scoreStruct : 0.0
scoreBuy += momentumLong ? scoreMomentum : 0.0
scoreBuy += flashSignal ? weightFlash : 0.0
scoreBuy += blinkSignal ? weightBlink : 0.0
scoreBuy += volumeSpike_AVP ? scoreVolume : 0.0
scoreBuy += priceStrength_Long ? scorePriceAction : 0.0
scoreBuy += reversalTrigger_Long ? scoreReversal : 0.0
scoreBuy += emaAlignment_Bull ? weightTrendAlign : 0.0
scoreBuy += strongUpTrend ? weightTrendAlign : 0.0
scoreBuy += highRisk_Long ? -1.2 : 0.0
scoreBuy += signalGreenDot ? 1.0 : 0.0
scoreBuy += isAMCUp ? 0.8 : 0.0
scoreBuy += isVssBuy ? 1.5 : 0.0
scoreBuy += isEMACrossUp ? 1.0 : 0.0
scoreBuy += signalRedX ? -1.0 : 0.0
scoreSell = 0.0
scoreSell += structSignalShort ? scoreStruct : 0.0
scoreSell += momentumShort ? scoreMomentum : 0.0
scoreSell += flashSignal ? weightFlash : 0.0
scoreSell += blinkSignal ? weightBlink : 0.0
scoreSell += volumeSpike_AVP ? scoreVolume : 0.0
scoreSell += priceStrength_Short ? scorePriceAction : 0.0
scoreSell += reversalTrigger_Short ? scoreReversal : 0.0
scoreSell += emaAlignment_Bear ? weightTrendAlign : 0.0
scoreSell += strongDownTrend ? weightTrendAlign : 0.0
scoreSell += highRisk_Short ? -1.2 : 0.0
scoreSell += signalRedX ? 1.0 : 0.0
scoreSell += isAMCDown ? 0.8 : 0.0
scoreSell += isVssSell ? 1.5 : 0.0
scoreSell += isEMACrossDown ? 1.0 : 0.0
scoreSell += signalGreenDot ? -1.0 : 0.0
compositeBuySignal = enableComposite and scoreBuy >= thresholdCompositeBuy
compositeSellSignal = enableComposite and scoreSell >= thresholdCompositeSell
if compositeBuySignal and compositeSellSignal
compositeBuySignal := false
compositeSellSignal := false
= calculateCompositeSignals()
// Final Entry Signals
entryCompositeBuySignal = compositeBuySignal and ta.rising(emaFast_ATG, 2)
entryCompositeSellSignal = compositeSellSignal and ta.falling(emaFast_ATG, 2)
Calculates weighted scores from independent modules and activates signals only when threshold requirements are met.
2. Smart Exit Hold Evaluation System
evaluateSmartHold() =>
compositeBuyRecentCount = 0
compositeSellRecentCount = 0
for i = 0 to signalLookbackBars - 1
compositeBuyRecentCount += compositeBuySignal ? 1 : 0
compositeSellRecentCount += compositeSellSignal ? 1 : 0
avgVolume = ta.sma(volume, 20)
volumeSpike = volume > avgVolume * volMultiplier
// MTF Bull/Bear conditions
mtf_bull = mtf_emaFast_final > mtf_emaSlow_final
mtf_bear = mtf_emaFast_final < mtf_emaSlow_final
emaBackupDivergence = math.abs(mtf_emaFast_backup - mtf_emaSlow_backup) / mtf_emaSlow_backup
emaBackupStrong = emaBackupDivergence > 0.008
mtfConflict_Long = inLong and mtf_bear and emaBackupStrong
mtfConflict_Short = inShort and mtf_bull and emaBackupStrong
// Layer 1: ATR-Based Dynamic Threshold (Market Volatility Intelligence)
atr_raw = ta.atr(atrLen)
atrValue = na(atr_raw) ? close * 0.02 : atr_raw
atrRatio = atrValue / close
dynamicThreshold = atrRatio > 0.02 ? 1.0 : (atrRatio > 0.01 ? 1.5 : 2.8)
// Layer 2: ROI-Conditional Time Intelligence (Selective Pressure)
timeMultiplier_Long = realROI >= 0 ? 1.0 : // Profitable positions: No time pressure
holdTimer_Long <= signalLookbackBars ? 1.0 : // Loss positions 1-8 bars: Base
holdTimer_Long <= signalLookbackBars * 2 ? 1.1 : // Loss positions 9-16 bars: +10% stricter
1.3 // Loss positions 17+ bars: +30% stricter
timeMultiplier_Short = realROI >= 0 ? 1.0 : // Profitable positions: No time pressure
holdTimer_Short <= signalLookbackBars ? 1.0 : // Loss positions 1-8 bars: Base
holdTimer_Short <= signalLookbackBars * 2 ? 1.1 : // Loss positions 9-16 bars: +10% stricter
1.3 // Loss positions 17+ bars: +30% stricter
// Dual-Layer Threshold Calculation
baseThreshold_Long = mtfConflict_Long ? dynamicThreshold + 1.0 : dynamicThreshold
baseThreshold_Short = mtfConflict_Short ? dynamicThreshold + 1.0 : dynamicThreshold
timeAdjustedThreshold_Long = baseThreshold_Long * timeMultiplier_Long
timeAdjustedThreshold_Short = baseThreshold_Short * timeMultiplier_Short
// Final Smart Hold Decision with Dual-Layer Intelligence
smartHold_Long = not mtfConflict_Long and smartScoreLong >= timeAdjustedThreshold_Long and compositeBuyRecentCount >= signalMinCount
smartHold_Short = not mtfConflict_Short and smartScoreShort >= timeAdjustedThreshold_Short and compositeSellRecentCount >= signalMinCount
= evaluateSmartHold()
Evaluates whether to hold positions past TP1/TP2/TP3 levels based on continued signal strength, volume confirmation, and multi-timeframe trend alignment
HOW TO USE THE STRATEGY
Step 1: Initial Setup
Apply strategy to your preferred timeframe (backtested on 15M)
Enable "Use Heikin-Ashi Base" for smoother signals in volatile markets
"Show EMA Lines" and "Show Ichimoku Cloud" are enabled for visual context
Set default quantities to match your risk management (5% equity default)
Step 2: Signal Recognition
Visual Signal Guide:
Visual Signal Guide - Complete Reference:
🔶 Red Diamond: Bearish momentum breakdown - short reversal signal
🔷 Blue Diamond: Strong bullish momentum - long reversal signal
🔵 Blue Dot: Volume-confirmed directional move - trend continuation
🟢 Green Dot: Bullish EMA crossover - trend reversal confirmation
🟠 Orange X: Oversold reversal setup - counter-trend opportunity
❌ Red X: Bearish EMA breakdown - trend reversal warning
✡ Star Uprising: Strong bullish convergence
💥 Ultra Entry: Ultra-rapid downward momentum acceleration
▲ VSS Long: Velocity-based bullish momentum confirmation
▼ VSS Short: Velocity-based bearish momentum confirmation
Step 3: Entry Execution
For Long Positions:
1. ✅ EMA1 crossed above EMA2 exactly 3 bars ago [ta.crossover(ema1,ema2) ]
2. ✅ Current EMA structure: EMA1 > EMA2 (maintained)
3. ✅ Composite score ≥ 5.0 points (6.5+ for 5-minute timeframes)
4. ✅ Cooldown period completed (no recent stop losses)
5. ✅ Volume spike confirmation (green dot/blue dot signals)
6. ✅ Bullish candle closes above EMA structure
For Short Positions:
1. ✅ EMA1 crossed below EMA2 exactly 3 bars ago [ta.crossunder(ema1,ema2) ]
2. ✅ Current EMA structure: EMA1 < EMA2 (maintained)
3. ✅ Composite score ≥ 5.4 points (7.0+ for 5-minute timeframes)
4. ✅ Cooldown period completed (no recent stop losses)
5. ✅ Momentum breakdown (red diamond/red X signals)
6. ✅ Bearish candle closes below EMA structure
🎯 Critical Timing Note: The strategy requires EMA crossover to have occurred 3 bars prior to entry, not at the current bar. This attempts to avoid premature entries and may improve signal reliability.
Step 4: Reading Market Context
EMA Ribbon Interpretation:
All EMAs ascending = Strong uptrend context
EMAs 1-3 above EMAs 4-8 = Bullish structure
Tight EMA spacing = Low volatility/consolidation
Wide EMA spacing = High volatility/trending
Ichimoku Cloud Context:
Price above cloud = Bullish environment
Price below cloud = Bearish environment
Cloud color intensity = Momentum strength
Thick cloud = Strong support/resistance
THE SMART EXIT GRID SYSTEM
Smart Exit Grid Approach:
The Smart Exit Grid uses dynamic hold evaluation that continuously analyzes market conditions after position entry. This differs from traditional fixed profit targets by adapting exit timing based on real-time signal strength.
How Smart Exit Grid System Works
The system operates through three evaluation phases:
Smart Score Calculation:
The smart score calculation aggregates 22 signal components in real-time, combining reversal warnings, continuation signals, trend alignment indicators, EMA structural analysis, and risk penalties into a numerical representation of market conditions. MTF analysis provides additional confirmation as a separate validation layer.
Signal Stack Management:
The per-tick signal accumulation system monitors 22 active signal types with MTF providing trend validation and conflict detection as a separate confirmation layer.
Take Profit Progression:
Smart Exit Activation:
The QRE system activates Smart Exit Grid immediately upon position entry. When strategy.entry() executes, the system initializes monitoring systems designed to track position progress.
Upon position opening, holdTimer begins counting, establishing the foundation for subsequent decisions. The Smart Exit Grid starts accumulating signals from entry, with all 22 signal components beginning real-time tracking when the trade opens.
The system operates on continuous evaluation where smartScoreLong and smartScoreShort calculate from the first tick after entry. QRE's approach is designed to capture market structure changes, trend deteriorations, or signal pattern shifts that can trigger protective exits even before the first take profit level is reached.
This activation creates a proactive position management framework. The 8-candle sliding window starts from entry, meaning that if market conditions change rapidly after entry - due to news events, liquidity shifts, or technical changes - the system can respond within the configured lookback period.
TP Markers as Reference Points:
The TP1, TP2, and TP3 levels function as reference points rather than mandatory exit triggers. When longTP1Hit or shortTP1Hit conditions activate, they serve as profit confirmation markers that inform the Smart Exit algorithm about achieved reward levels, but don't automatically initiate position closure.
These TP markers enhance the Smart Exit decision matrix by providing profit context to ongoing signal evaluation. The system recognizes when positions have achieved target returns, but the actual exit decision remains governed by continuous smart score evaluation and signal stack analysis.
TP2 Reached: Enhanced Monitoring
TP2 represents significant profit capture with additional monitoring features:
This approach is designed to help avoid premature profit-taking during trending conditions. If TP2 is reached but smartScoreLong remains above the dynamic threshold and the 8-candle sliding window shows persistent signals, the position continues holding. If market structure deteriorates before reaching TP2, the Smart Exit can trigger closure based on signal analysis.
The visual TP circles that appear when levels are reached serve as performance tracking tools, allowing users to see how frequently entries achieve various profit levels while understanding that actual exit timing depends on market structure analysis.
Risk Management Systems:
Operating independently from the Smart Exit Grid are two risk management systems: the Trap Wick Detection Protocol and the Stop Loss Mechanism. These systems maintain override authority over other exit logic.
The Trap Wick System monitors for conditionBearTrapExit during long positions and conditionBullTrapExit during short positions. When detected, these conditions trigger position closure with state reset, bypassing Smart Exit evaluations. This system recognizes that certain candlestick patterns may indicate reversal risk.
Volatility Exit Monitoring: The strategy monitors for isStrongBearCandle combined with conditionBearTrapExit, recognizing when market structure may be shifting.
Volume Validation: Before exiting on volatility, the strategy requires volume confirmation: volume > ta.sma(volume, 20) * 1.8. This is designed to filter exits on weak, low-volume movements.
The Stop Loss Mechanism operates through multiple triggers including traditional price-based stops (longSLHit, shortSLHit) and early exit conditions based on smart score deterioration combined with negative ROI. The early exit logic activates when smartScoreLong < 1.0 or smartScoreShort < 1.0 while realROI < -0.9%.
These risk management systems are designed so that risk scenarios can trigger protective closure with state reset across all 22 signal counters, TP tracking variables, and smart exit states.
This architecture - Smart Exit activation, TP markers as navigation tools, and independent risk management - creates a position management system that adapts to market conditions while maintaining risk discipline through dedicated protection protocols.
TP3 Reached: Enhanced Protection
Once TP3 is hit, the strategy shifts into enhanced monitoring:
EMA Structure Monitoring: isEMAStructureDown becomes a primary exit trigger
MTF Alignment: The higher timeframe receives increased consideration
Wick Trap Priority: conditionBearTrapExit becomes an immediate exit signal
Approach Differences:
Traditional Fixed Exits:
Exit at predetermined levels regardless of market conditions
May exit during trend continuation
May exit before trend completion
Limited adaptation to changing volatility
Smart Exit Grid Approach:
Adaptive timing based on signal conditions
Exits when supporting signals weaken
Multi-timeframe validation for trend confirmation
Volume confirmation requirements for holds
Structural monitoring for trend analysis
Dynamic ATR-Based Smart Score Threshold System
Market Volatility Adaptive Scoring
// Real-time ATR Analysis
atr_raw = ta.atr(atrLen)
atrValue = na(atr_raw) ? close * 0.02 : atr_raw
atrRatio = atrValue / close
// Three-Tier Dynamic Threshold Matrix
dynamicThreshold = atrRatio > 0.02 ? 1.0 : // High volatility: Lower threshold
(atrRatio > 0.01 ? 1.5 : // Medium volatility: Standard
2.8) // Low volatility: Higher threshold
The market volatility adaptive scoring calculates real-time ATR with a 2% fallback for new markets. The atrRatio represents the relationship between current volatility and price, creating a foundation for threshold adjustment.
The three-tier dynamic threshold matrix responds to market conditions by adjusting requirements based on volatility levels: lowering thresholds during high volatility periods above 2% ATR ratio to 1.0 points, maintaining standard requirements at 1.5 points for medium volatility between 1-2%, and raising standards to 2.8 points during low volatility periods below 1%.
Profit-Loss Adaptive Management:
The system applies different evaluation criteria based on position performance:
Winning Positions (realROI ≥ 0%):
→ timeMultiplier = 1.0 (No additional pressure)
→ Maintains base threshold requirements
→ Allows natural progression to TP2/TP3 levels
Losing Positions (realROI < 0%):
→ Progressive time pressure activated
→ Increasingly strict requirements over time
→ Faster decision-making on underperforming trades
ROI-Adaptive Smart Hold Decision Process:
The strategy uses a profit-loss adaptive system:
Winning Position Management (ROI ≥ 0%):
✅ Standard threshold requirements maintained
✅ No additional time-based pressure applied
✅ Allows positions to progress toward TP2/TP3 levels
✅ timeMultiplier remains at 1.0 regardless of hold duration
Losing Position Management (ROI < 0%):
⚠️ Time-based threshold adjustments activated
⚠️ Progressive increase in required signal strength over time
⚠️ Earlier exit evaluation on underperforming positions
⚠️ timeMultiplier increases from 1.0 → 1.1 → 1.3 based on hold duration
Real-Time Monitoring:
Monitor Analysis Table → "Smart" filter → "Score" vs "Dynamic Threshold"
Winning positions: Evaluation based on signal strength deterioration only
Losing positions: Evaluation considers both signal strength and progressive time adjustments
Breakeven positions (0% ROI): Treated as winning positions - no time adjustments
This approach differentiates between winning and losing positions in the hold evaluation process, requiring higher signal thresholds for extended holding of losing positions while maintaining standard requirements for winning ones.
ROI-Conditional Decision Matrix Examples:
Scenario 1 - Winning Position in Any Market:
Position ROI: +0.8% → timeMultiplier = 1.0 (regardless of hold time)
ATR Medium (1.2%) → dynamicThreshold = 1.5
Final Threshold = 1.5 × 1.0 = 1.5 points ✅ Position continues
Scenario 2 - Losing Position, Extended Hold:
Position ROI: -0.5% → Time pressure activated
Hold Time: 20 bars → timeMultiplier = 1.3
ATR Low (0.8%) → dynamicThreshold = 2.8
Final Threshold = 2.8 × 1.3 = 3.64 points ⚡ Enhanced requirements
Scenario 3 - Fresh Losing Position:
Position ROI: -0.3% → Time pressure activated
Hold Time: 5 bars → timeMultiplier = 1.0 (still early)
ATR High (2.1%) → dynamicThreshold = 1.0
Final Threshold = 1.0 × 1.0 = 1.0 points 📊 Recovery opportunity
Scenario 4 - Breakeven Position:
Position ROI: 0.0% → timeMultiplier = 1.0 (no pressure)
Hold Time: 15 bars → No time penalty applied
Final Threshold = dynamicThreshold only ⚖️ Neutral treatment
🔄8-Candle Sliding Window Signal Rotation System
Composite Signal Counting Mechanism
// Dynamic Lookback Window (configurable: default 8)
signalLookbackBars = input.int(8, "Composite Lookback Bars", minval=1, maxval=50)
// Rolling Signal Analysis
compositeBuyRecentCount = 0
compositeSellRecentCount = 0
for i = 0 to signalLookbackBars - 1
compositeBuyRecentCount += compositeBuySignal ? 1 : 0
compositeSellRecentCount += compositeSellSignal ? 1 : 0
Candle Flow Example (8-bar window):
→
✓ ✓ ✗ ✓ ✗ ✓ ✗ ✓ 🗑️
New Signal Count = 5/8 signals in window
Threshold Check: 5 ≥ signalMinCount (2) = HOLD CONFIRMED
Signal Decay & Refresh Mechanism
// Signal Persistence Tracking
if compositeBuyRecentCount >= signalMinCount
smartHold_Long = true
else
smartHold_Long = false
The composite signal counting operates through a configurable sliding window. The system maintains rolling counters that scan backward through the specified number of candles.
During each evaluation cycle, the algorithm iterates through historical bars, incrementing counters when composite signals are detected. This creates a dynamic signal persistence measurement where recent signal density determines holding decisions.
The sliding window rotation functions like a moving conveyor belt where new signals enter while the oldest signals drop off. For example, in an 8-bar window, if 5 out of 8 recent candles showed composite buy signals, and the minimum required count is 2, the system confirms the hold condition. As new bars form, the window slides forward, potentially changing the signal count and triggering exit conditions when signal density falls below the threshold.
Signal decay and refresh occur continuously where smartHold_Long remains true only when compositeBuyRecentCount exceeds signalMinCount. When recent signal density drops below the minimum requirement, the system switches to exit mode.
Advanced Signal Stack Management - 22-Signal Real-Time Evaluation
// Long Position Signal Stacking (calc_on_every_tick=true)
if inLong
// Primary Reversal Signals
if signalRedDiamond: signalCountRedDiamond += 1 // -0.5 points
if signalStarUprising: signalCountStarUprising += 1 // +1.5 points
if entryUltraShort: signalCountUltra += 1 // -1.0 points
// Trend Confirmation Signals
if strongUpTrend: trendUpCount_Long += 1 // +1.5 points
if emaAlignment_Bull: bullAlignCount_Long += 1 // +1.0 points
// Risk Assessment Signals
if highRisk_Long: riskCount_Long += 1 // -1.5 points
if topZone: tzoneCount_Long += 1 // -0.5 points
The per-tick signal accumulation system operates with calc_on_every_tick=true for real-time responsiveness. During long positions, the system monitors primary reversal signals where Red Diamond signals subtract 0.5 points as reversal warnings, Star Uprising adds 1.5 points for continuation signals, and Ultra Short signals deduct 1.0 points as counter-trend warnings.
Trend confirmation signals provide weighted scoring where strongUpTrend adds 1.5 points for aligned momentum, emaAlignment_Bull contributes 1.0 point for structural support, and various EMA-based confirmations contribute to the overall score. Risk assessment signals apply negative weighting where highRisk_Long situations subtract 1.5 points, topZone conditions deduct 0.5 points, and other risk factors create defensive scoring adjustments.
The smart score calculation aggregates all 22 components in real-time, combining reversal warnings, continuation signals, trend alignment indicators, EMA structural analysis, and risk penalties into a numerical representation of market conditions. This score updates continuously, providing the foundation for hold-or-exit decisions.
MULTI-TIMEFRAME (MTF) SYSTEM
MTF Data Collection
The strategy requests higher timeframe data (default 30-minute) for trend confirmation:
= request.security(syminfo.tickerid, mtfTimeframe, , lookahead=barmerge.lookahead_off, gaps=barmerge.gaps_off)
MTF Watchtower System - Implementation Logic
The system employs a timeframe discrimination protocol where currentTFInMinutes is compared against a 30-minute threshold. This creates different operational behavior between timeframes:
📊 Timeframe Testing Results:
30M+ charts: Full MTF confirmation → Tested with full features
15M charts: Local EMA + adjusted parameters → Standard testing baseline
5M charts: Local EMA only → Requires parameter adjustment
1M charts: High noise → Limited testing conducted
When the chart timeframe is 30 minutes or above, the strategy activates useMTF = true and requests external MTF data through request.security(). For timeframes below 30 minutes, including your 5-minute setup, the system deliberately uses local EMA calculations to avoid MTF lag and data inconsistencies.
The triple-layer data sourcing architecture works as follows: timeframes from 1 minute to 29 minutes rely on chart-based EMA calculations for immediate responsiveness. Timeframes of 30 minutes and above utilize MTF data through the security function, with a backup system that doubles the EMA length (emaLen * 2) if MTF data fails. When MTF data is unavailable or invalid, the system falls back to local EMA as the final safety net.
Data validation occurs through a pipeline where mtf_dataValid checks not only for non-null values but also verifies that EMA values are positive above zero. The system tracks data sources through mtf_dataSource which displays "MTF Data" for successful external requests, "Backup EMA" for failed MTF with backup system active, or "Chart EMA" for local calculations.
🔄 MTF Smart Score Caching & Recheck System
// Cache Update Decision Logic
mtfSmartIntervalSec = input.int(300, "Smart Grid Recheck Interval (sec)") // 5-minute cache
canRecheckSmartScore = na(timenow) ? false :
(na(lastCheckTime) or (timenow - lastCheckTime) > mtfSmartIntervalSec * 1000)
// Cache Management
if canRecheckSmartScore
lastCheckTime := timenow
cachedSmartScoreLong := smartScoreLong // Store current calculation
cachedSmartScoreShort := smartScoreShort
The performance-optimized caching system addresses the computational intensity of continuous MTF analysis through intelligent interval management. The mtfSmartIntervalSec parameter, defaulting to 300 seconds (5 minutes), determines cache refresh frequency. The system evaluates canRecheckSmartScore by comparing current time against lastCheckTime plus the configured interval.
When cache updates trigger, the system stores current calculations in cachedSmartScoreLong and cachedSmartScoreShort, creating stable reference points that reduce excessive MTF requests. This cache management balances computational efficiency with analytical accuracy.
The cache versus real-time hybrid system creates a multi-layered decision matrix where immediate signals update every tick for responsive market reaction, cached MTF scores refresh every 5 minutes for stability filtering, dynamic thresholds recalculate every bar for volatility adaptation, and sliding window analysis updates every bar for trend persistence validation.
This architecture balances real-time signal detection with multi-timeframe strategic validation, creating adaptive trading intelligence that responds immediately to market changes while maintaining strategic stability through cached analysis and volatility-adjusted decision thresholds.
⚡The Execution Section Deep Dive
The execution section represents the culmination of all previous systems – where analysis transforms into action.
🚪 Entry Execution: The Gateway Protocol
Primary Entry Validation:
Entry isn't just about seeing a signal – it's about passing through multiple security checkpoints, each designed to filter out low-quality opportunities.
Stage 1: Signal Confirmation
entryCompositeBuySignal must be TRUE for longs
entryCompositeSellSignal must be TRUE for shorts
Stage 2: Enhanced Entry Validation
The strategy employs an "OR" logic system that recognizes different types of market opportunities:
Path A - Trend Reversal Entry:
When emaTrendReversal_Long triggers, it indicates the market structure is shifting in favor of the trade direction. This isn't just about a single EMA crossing – it represents a change in market momentum that experienced traders recognize as potential high-probability setups.
Path B - Momentum Breakout Entry:
The strongBullMomentum condition is where QRE identifies accelerating market conditions:
Criteria:
EMA1 rising for 3+ candles AND
EMA2 rising for 2+ candles AND
Close > 10-period high
This combination captures those explosive moves where the market doesn't just trend – it accelerates, creating momentum-driven opportunities.
Path C - Recovery Entry:
When previous exit states are clean (no recent stop losses), the strategy permits entry based purely on signal strength. This pathway is designed to help avoid the strategy becoming overly cautious after successful trades.
🛡️ The Priority Exit Matrix: When Rules Collide
Not all exit signals are created equal. QRE uses a strict hierarchy that is designed to avoid conflicting signals from causing hesitation:
Priority Level 1 - Exception Exits (Immediate Action):
Condition: TP3 reached AND Wick Trap detected
Action: Immediate exit regardless of other signals
Rationale: Historical analysis suggests wick traps at TP3 may indicate potential reversals
Priority Level 2 - Structural Breakdown:
Condition: TP3 active AND EMA structure deteriorating AND Smart Score insufficient
Logic: isEMAStructureDown AND NOT smartHold_Long
This represents the strategy recognizing that the underlying market structure that justified the trade is failing. It's like a building inspector identifying structural issues – you don't wait for additional confirmation.
Priority Level 3 - Enhanced Volatility Exits:
Conditions: TP2 active AND Strong counter-candle AND Wick trap AND Volume spike
Logic: Multiple confirmation required to reduce false exits
Priority Level 4 - Standard Smart Score Exits:
Condition: Any TP level active AND smartHold evaluates to FALSE
This is the bread-and-butter exit logic where signal deterioration triggers exit
⚖️ Stop Loss Management: Risk Control Protocol
Dual Stop Loss System:
QRE provides two stop loss modes that users can select based on their preference:
Fixed Mode (Default - useAdaptiveSL = false):
Uses predetermined percentage levels regardless of market volatility:
- Long SL = entryPrice × (1 - fixedRiskP - slipBuffer)
- Short SL = entryPrice × (1 + fixedRiskP + slipBuffer)
- Default: 0.6% risk + 0.3% slippage buffer = 0.9% total stop
- Consistent and predictable stop loss levels
- Recommended for users who prefer stable risk parameters
Adaptive Mode (Optional - useAdaptiveSL = true):
Dynamic system that adjusts stop loss based on market volatility:
- Base Calculation uses ATR (Average True Range)
- Long SL = entryPrice × (1 - (ATR × atrMultSL) / entryPrice - slipBuffer)
- Short SL = entryPrice × (1 + (ATR × atrMultSL) / entryPrice + slipBuffer)
- Automatically widens stops during high volatility periods
- Tightens stops during low volatility periods
- Advanced users can enable for volatility-adaptive risk management
Trend Multiplier Enhancement (Both Modes):
When strongUpTrend is detected for long positions, the stop loss receives 1.5x breathing room. Strong trends often have deeper retracements before continuing. This is designed to help avoid the strategy being shaken out of active trades by normal market noise.
Mode Selection Guidance:
- New Users: Start with Fixed Mode for predictable risk levels
- Experienced Users: Consider Adaptive Mode for volatility-responsive stops
- Volatile Markets: Adaptive Mode may provide better stop placement
- Stable Markets: Fixed Mode often sufficient for consistent risk management
Early Exit Conditions:
Beyond traditional stop losses, QRE implements "smart stops" that trigger before price-based stops:
Early Long Exit: (smartScoreLong < 1.0 OR prev5BearCandles) AND realROI < -0.9%
🔄 State Management: The Memory System
Complete State Reset Protocol:
When a position closes, QRE doesn't just wipe the slate clean – it performs a methodical reset:
TP State Cleanup:
All Boolean flags: tp1/tp2/tp3HitBefore → FALSE
All Reached flags: tp1/tp2/tp3Reached → FALSE
All Active flags: tp1/tp2/tp3HoldActive → FALSE
Signal Counter Reset:
Every one of the 22 signal counters returns to zero.
This is designed to avoid signal "ghosting" where old signals influence new trades.
Memory Preservation:
While operational states reset, certain information is preserved for learning:
killReasonLong/Short: Why did this trade end?
lastExitWasTP1/TP2/TP3: What was the exit quality?
reEntryCount: How many consecutive re-entries have occurred?
🔄 Re-Entry Logic: The Comeback System
Re-Entry Conditions Matrix:
QRE implements a re-entry system that recognizes not all exits are created equal:
TP-Based Re-Entry (Enabled):
Criteria: Previous exit was TP1, TP2, or TP3
Cooldown: Minimal or bypassed entirely
Logic: Target-based exits indicate potentially viable market conditions
EMA-Based Re-Entry (Conditional):
Criteria: Previous exit was EMA-based (structural change)
Requirements: Must wait for EMA confirmation in new direction
Minimum Wait: 5 candles
Advanced Re-Entry Features:
When adjustReEntryTargets is enabled, the strategy becomes more aggressive with re-entries:
Target Adjustment: TP1 multiplied by reEntryTP1Mult (default 2.0)
Stop Adjustment: SL multiplied by reEntrySLMult (default 1.5)
Logic: If we're confident enough to re-enter, we should be confident enough to hold for bigger moves
Performance Tracking: Strategy tracks re-entry win rate, average ROI, and total performance separately from initial entries for optimization analysis.
📊 Exit Reason Analytics: Learning from Every Trade
Kill Reason Tracking:
Every exit is categorized and stored:
"TP3 Exit–Wick Trap": Exit at target level with wick pattern detection
"Smart Exit–EMA Down": Structural breakdown exit
"Smart Exit–Volatility": Volatility-based protection exit
"Exit Post-TP1/TP2/TP3": Standard smart exit progression
"Long SL Exit" / "Short SL Exit": Stop loss exits
Performance Differentiation:
The strategy tracks performance by exit type, allowing for continuous analysis:
TP-based exits: Achieved target levels, analyze for pattern improvement
EMA-based exits: Mixed results, analyze for pattern improvement
SL-based exits: Learning opportunities, adjust entry criteria
Volatility exits: Protective measures, monitor performance
🎛️ Trailing Stop Implementation:
Conditional Trailing Activation:
Activation Criteria: Position profitable beyond trailingStartPct AND
(TP hold active OR re-entry trade)
Dynamic Trailing Logic:
Unlike simple trailing stops, QRE's implementation considers market context:
Trending Markets: Wider trail offsets to avoid whipsaws
Volatile Markets: Tighter offsets to protect gains
Re-Entry Trades: Enhanced trailing to maximize second-chance opportunities
Return-to-Entry Protection:
When deactivateOnReturn is enabled, the strategy will close positions that return to entry level after being profitable. This is designed to help avoid the frustration of watching profitable trades turn into losers.
🧠 How It All Works Together
The beauty of QRE lies not in any single component, but in how everything integrates:
The Entry Decision: Multiple pathways are designed to help identify opportunities while maintaining filtering standards.
The Progression System: Each TP level unlocks new protection features, like achieving ranks in a video game.
The Exit Matrix: Prioritized decision-making aims to reduce analysis paralysis while providing appropriate responses to different market conditions.
The Memory System: Learning from each trade while preventing contamination between separate opportunities.
The Re-Entry Logic: Re-entry system that balances opportunity with risk management.
This creates a trading system where entry conditions filter for quality, progression systems adapt to changing market conditions, exit priorities handle conflicting signals intelligently, memory systems learn from each trade cycle, and re-entry logic maximizes opportunities while managing risk exposure.
📊 ANALYSIS TABLE INTERPRETATION -
⚙️ Enabling Analysis Mode
Navigate to strategy settings → "Testing & Analysis" → Enable "Show Analysis Table". The Analysis Table displays different information based on the selected test filter and provides real-time insight into all strategy components, helping users understand current market conditions, position status, and system decision-making processes.
📋 Filter Mode Interpretations
"All" Mode (Default View):
Composite Section:
Buy Score: Aggregated strength from all 22 bullish signals (threshold 5.0+ triggers entry consideration)
Sell Score: Aggregated strength from all 22 bearish signals (threshold 5.4+ triggers entry consideration)
APEX Filters:
ATG Trend: Shows current trend direction analysis
Indicates whether momentum filters are aligned for directional bias
ReEntry Section:
Most Recent Exit: Displays exit type and timeframe since last position closure
Status: Shows if ReEntry system is Ready/Waiting/Disabled
Count: Current re-entry attempts versus maximum allowed attempts
Position Section (When Active):
Status: Current position state (LONG/SHORT/FLAT)
ROI: Dual calculation showing Custom vs Real ROI percentages
Entry Price: Original position entry level
Current Price: Live market price for comparison
TP Tracking: Progress toward profit targets
"Smart" Filter (Critical for Active Positions):
Smart Exit Section:
Hold Timer: Time elapsed since position opened (bar-based counting)
Status: Whether Smart Exit Grid is Enabled/Disabled
Score: Current smart score calculation from 22-component matrix
Dynamic Threshold: ATR-based minimum score required for holding
Final Threshold: Time and ROI-adjusted threshold actually used for decisions
Score Check: Pass/Fail based on Score vs Final Threshold comparison
Smart Hold: Current hold decision status
Final Hold: Final recommendation based on all factors
🎯 Advanced Smart Exit Debugging - ROI & Time-Based Threshold System
Understanding the Multi-Layer Threshold System:
Layer 1: Dynamic Threshold (ATR-Based)
atrRatio = ATR / close
dynamicThreshold = atrRatio > 0.02 ? 1.0 : // High volatility: Lower threshold
(atrRatio > 0.01 ? 1.5 : // Medium volatility: Standard
2.8) // Low volatility: Higher threshold
Layer 2: Time Multiplier (ROI & Duration-Based)
Winning Positions (ROI ≥ 0%):
→ timeMultiplier = 1.0 (No time pressure, regardless of hold duration)
Losing Positions (ROI < 0%):
→ holdTimer ≤ 8 bars: timeMultiplier = 1.0 (Early stage, standard requirements)
→ holdTimer 9-16 bars: timeMultiplier = 1.1 (10% stricter requirements)
→ holdTimer 17+ bars: timeMultiplier = 1.3 (30% stricter requirements)
Layer 3: Final Threshold Calculation
finalThreshold = dynamicThreshold × timeMultiplier
Examples:
- Winning Position: 2.8 × 1.0 = 2.8 (Always standard)
- Losing Position (Early): 2.8 × 1.0 = 2.8 (Same as winning initially)
- Losing Position (Extended): 2.8 × 1.3 = 3.64 (Much stricter)
Real-Time Debugging Display:
Smart Exit Section shows:
Score: 3.5 → Current smartScoreLong/Short value
Dynamic Threshold: 2.8 → Base ATR-calculated threshold
Final Threshold: 3.64 (ATR×1.3) → Actual threshold used for decisions
Score Check: FAIL (3.5 vs 3.64) → Pass/Fail based on final comparison
Final Hold: NO HOLD → Actual system decision
Position Status Indicators:
Winner + Early: ATR×1.0 (No pressure)
Winner + Extended: ATR×1.0 (No pressure - winners can run indefinitely)
Loser + Early: ATR×1.0 (Recovery opportunity)
Loser + Extended: ATR×1.1 or ATR×1.3 (Increasing pressure to exit)
MTF Section:
Data Source: Shows whether using MTF Data/EMA Backup/Local EMA
Timeframe: Configured watchtower timeframe setting
Data Valid: Confirms successful MTF data retrieval status
Trend Signal: Higher timeframe directional bias analysis
Close Price: MTF price data availability confirmation
"Composite" Filter:
Composite Section:
Buy Score: Real-time weighted scoring from multiple indicators
Sell Score: Opposing directional signal strength
Threshold: Minimum scores required for signal activation
Components:
Flash/Blink: Momentum acceleration indicators (F = Flash active, B = Blink active)
Individual filter contributions showing which specific signals are firing
"ReEntry" Filter:
ReEntry System:
System: Shows if re-entry feature is Enabled/Disabled
Eligibility: Conditions for new entries in each direction
Performance: Success metrics of re-entry attempts when enabled
🎯 Key Status Indicators
Status Column Symbols:
✓ = Condition met / System active / Signal valid
✗ = Condition not met / System inactive / No signal
⏳ = Cooldown active (waiting period)
✅ = Ready state / Good condition
🔄 = Processing / Transitioning state
🔍 Critical Reading Guidelines
For Active Positions - Smart Exit Priority Reading:
1. First Check Position Type:
ROI ≥ 0% = Winning Position (Standard requirements)
ROI < 0% = Losing Position (Progressive requirements)
2. Check Hold Duration:
Early Stage (≤8 bars): Standard multiplier regardless of ROI
Extended Stage (9-16 bars): Slight pressure on losing positions
Long Stage (17+ bars): Strong pressure on losing positions
3. Score vs Final Threshold Analysis:
Score ≥ Final Threshold = HOLD (Continue position)
Score < Final Threshold = EXIT (Close position)
Watch for timeMultiplier changes as position duration increases
4. Understanding "Why No Hold?"
Common scenarios when Score Check shows FAIL:
Losing position held too long (timeMultiplier increased to 1.1 or 1.3)
Low volatility period (dynamic threshold raised to 2.8)
Signal deterioration (smart score dropped below required level)
MTF conflict (higher timeframe opposing position direction)
For Entry Signal Analysis:
Composite Score Reading: Signal strength relative to threshold requirements
Component Analysis: Individual filter contributions to overall score
EMA Structure: Confirm 3-bar crossover requirement met
Cooldown Status: Ensure sufficient time passed since last exit
For ReEntry Opportunities (when enabled):
System Status: Availability and eligibility for re-engagement
Exit Type Analysis: TP-based exits enable immediate re-entry, SL-based exits require cooldown
Condition Monitoring: Requirements for potential re-entry signals
Debugging Common Issues:
Issue: "Score is high but no hold?"
→ Check Final Threshold vs Score (not Dynamic Threshold)
→ Losing position may have increased timeMultiplier
→ Extended hold duration applying pressure
Issue: "Why different thresholds for same score?"
→ Position ROI status affects multiplier
→ Time elapsed since entry affects multiplier
→ Market volatility affects base threshold
Issue: "MTF conflicts with local signals?"
→ Higher timeframe trend opposing position
→ System designed to exit on MTF conflicts
→ Check MTF Data Valid status
⚡ Performance Optimization Notes
For Better Performance:
Analysis table updates may impact performance on some devices
Use specific filters rather than "All" mode for focused monitoring
Consider disabling during live trading for optimal chart performance
Enable only when needed for debugging or analysis
Strategic Usage:
Monitor "Smart" filter when positions are active for exit timing decisions
Use "Composite" filter during setup phases for signal strength analysis
Reference "ReEntry" filter after position closures for re-engagement opportunities
Track Final Threshold changes to understand exit pressure evolution
Advanced Debugging Workflow:
Position Entry Analysis:
Check Composite score vs threshold
Verify EMA crossover timing (3 bars prior)
Confirm cooldown completion
Hold Decision Monitoring:
Track Score vs Final Threshold progression
Monitor timeMultiplier changes over time
Watch for MTF conflicts
Exit Timing Analysis:
Identify which threshold layer caused exit
Track performance by exit type
Analyze re-entry eligibility
This analysis system provides transparency into strategy decision-making processes, allowing users to understand how signals are generated and positions are managed according to the programmed logic during various market conditions and position states.
SIGNAL TYPES AND CHARACTERISTICS
🔥 Core Momentum Signals
Flash Signal
Calculation: ta.rma(math.abs(close - close ), 5) > ta.sma(math.abs(close - close ), 7)
Purpose: Detects sudden price acceleration using smoothed momentum comparison
Characteristics: Triggers when recent price movement exceeds historical average movement
Usage: Primary momentum confirmation across multiple composite calculations
Weight: 1.3 points in composite scoring
Blink Signal
Calculation: math.abs(ta.change(close, 1)) > ta.sma(math.abs(ta.change(close, 1)), 5)
Purpose: Identifies immediate price velocity spikes
Characteristics: More sensitive than Flash, captures single-bar momentum bursts
Usage: Secondary momentum confirmation, often paired with Flash
Weight: 1.3 points in composite scoring
⚡ Advanced Composite Signals
Apex Pulse Signal
Calculation: apexAngleValue > 30 or apexAngleValue < -30
Purpose: Detects extreme EMA angle momentum
Characteristics: Identifies when trend angle exceeds ±30 degrees
Usage: Confirms directional momentum strength in trend-following scenarios
Pressure Surge Signal
Calculation: volSpike_AVP and strongTrendUp_ATG
Purpose: Combines volume expansion with trend confirmation
Characteristics: Requires both volume spike and strong uptrend simultaneously
Usage: bullish signal for trend continuation
Shift Wick Signal
Calculation: ta.crossunder(ema1, ema2) and isWickTrapDetected and directionFlip
Purpose: Detects bearish reversal with wick trap confirmation
Characteristics: Combines EMA crossunder with upper wick dominance and directional flip
Usage: Reversal signal for trend change identification
🛡️ Trap Exit Protection Signals
Bear Trap Exit
Calculation: isUpperWickTrap and isBearEngulfNow
Conditions: Previous bullish candle with 80%+ upper wick, followed by current bearish engulfing
Purpose: Emergency exit signal for long positions
Priority: Highest - overrides all other hold conditions
Action: Immediate position closure with full state reset
Bull Trap Exit
Calculation: isLowerWickTrap and isBullEngulfNow
Conditions: Previous bearish candle with 80%+ lower wick, followed by current bullish engulfing
Purpose: Emergency exit signal for short positions
Priority: Highest - overrides all other hold conditions
Action: Immediate position closure with full state reset
📊 Technical Analysis Foundation Signals
RSI-MFI Hybrid System
Base Calculation: (ta.rsi(close, 14) + ta.mfi(close, 14)) / 2
Oversold Threshold: < 35
Overbought Threshold: > 65
Weak Condition: < 35 and declining
Strong Condition: > 65 and rising
Usage: Momentum confirmation and reversal identification
ADX-DMI Trend Classification
Strong Up Trend: (adx > 25 and diplus > diminus and (diplus - diminus) > 5) or (ema1 > ema2 and ema2 > ema3 and ta.rising(ema2, 3))
Strong Down Trend: (adx > 20 and diminus > diplus - 5) or (ema1 < ema2 and ta.falling(ema1, 3))
Trend Weakening: adx < adx and adx < adx
Usage: Primary trend direction confirmation
Bollinger Band Squeeze Detection
Calculation: bbWidth < ta.lowest(bbWidth, 20) * 1.2
Purpose: Identifies low volatility periods before breakouts
Usage: Entry filter - avoids trades during consolidation
🎨 Visual Signal Indicators
Red X Signal
Calculation: isBearCandle and ta.crossunder(ema1, ema2)
Visual: Red X above price
Purpose: Bearish EMA crossunder with confirming candle
Composite Weight: +1.0 for short positions, -1.0 for long positions
Characteristics: Simple but effective trend change indicator
Green Dot Signal
Calculation: isBullCandle and ta.crossover(ema1, ema2)
Visual: Green dot below price
Purpose: Bullish EMA crossover with confirming candle
Composite Weight: +1.0 for long positions, -1.0 for short positions
Characteristics: Entry confirmation for trend-following strategies
Blue Diamond Signal
Trigger Conditions: amcBuySignal and score >= 4
Scoring Components: 11 different technical conditions
Key Requirements: AMC bullish + momentum rise + EMA expansion + volume confirmation
Visual: Blue diamond below price
Purpose: Bullish reversal or continuation signal
Characteristics: Multi-factor confirmation requiring 4+ technical alignments
Red Diamond Signal
Trigger Conditions: amcSellSignal and score >= 5
Scoring Components: 11 different technical conditions (stricter than Blue Diamond)
Key Requirements: AMC bearish + momentum crash + EMA compression + volume decline
Visual: Red diamond above price
Purpose: Potential bearish reversal or continuation signal
Characteristics: Requires higher threshold (5 vs 4) for more selective triggering
🔵 Specialized Detection Signals
Blue Dot Signal
Calculation: volumePulse and isCandleStrong and volIsHigh
Requirements: Volume > 2.0x MA, strong candle body > 35% of range, volume MA > 55
Purpose: Volume-confirmed momentum signal
Visual: Blue dot above price
Characteristics: Volume-centric signal for high-liquidity environments
Orange X Signal
Calculation: Complex multi-factor oversold reversal detection
Requirements: AMC oversold + wick trap + flash/blink + RSI-MFI oversold + bullish flip
Purpose: Oversold bounce signal with multiple confirmations
Visual: Orange X below price
Characteristics: Reversal signal requiring 5+ simultaneous conditions
VSS (Velocity Signal System)
Components: Volume spike + EMA angle + trend direction
Buy Signal: vssTrigger and vssTrendDir == 1
Sell Signal: vssTrigger and vssTrendDir == -1
Visual: Green/Red triangles
Purpose: Velocity-based momentum detection
Characteristics: Fast-response signal for momentum trading
⭐ Elite Composite Signals
Star Uprising Signal
Base Requirements: entryCompositeBuySignal and echoBodyLong and strongUpTrend and isAMCUp
Additional Confirmations: RSI hybrid strong + not high risk
Special Conditions: At bottom zone OR RSI bottom bounce OR strong volume bounce
Visual: Star symbol below price
Purpose: Bullish reversal signal from oversold conditions
Characteristics: Most selective bullish signal requiring multiple confirmations
Ultra Short Signal
Scoring System: 7-component scoring requiring 4+ points
Key Components: EMA trap + volume decline + RSI weakness + composite confirmation
Additional Requirements: Falling EMA structure + volume spike + flash confirmation
Visual: Explosion emoji above price
Purpose: Aggressive short entry for trend reversal or continuation
Characteristics: Complex multi-layered signal for experienced short selling
🎯 Composite Signal Architecture
Enhanced Composite Scoring
Long Composite: 15+ weighted components including structure, momentum, flash/blink, volume, price action, reversal triggers, trend alignment
Short Composite: Mirror structure with bearish bias
Threshold: 5.0 points required for signal activation
Conflict Resolution: If both long and short signals trigger simultaneously, both are disabled
Final Validation: Requires EMA momentum confirmation (ta.rising(emaFast_ATG, 2) for longs, ta.falling(emaFast_ATG, 2) for shorts)
Risk Assessment Integration
High Risk Long: RSI > 70 OR close > upper Bollinger Band 80%
High Risk Short: RSI < 30 OR close < lower Bollinger Band 80%
Zone Analysis: Top zone (95% of 50-bar high) vs Bottom zone (105% of 50-bar low)
Risk Penalty: High risk conditions subtract 1.5 points from composite scores
This signal architecture creates a multi-layered detection system where simple momentum signals provide foundation, technical analysis adds structure, visual indicators offer clarity, specialized detectors capture different market conditions, and composite signals identify potential opportunities while integrated risk assessment is designed to filter risky entries.
VISUAL FEATURES SHOWCASE
Ichimoku Cloud Visualization
Dynamic Color Intensity: Cloud transparency adapts to momentum strength - darker colors indicate stronger directional moves, while lighter transparency shows weakening momentum phases.
Gradient Color Mapping: Bullish momentum renders blue-purple spectrum with increasing opacity, while bearish momentum displays corresponding color gradients with intensity-based transparency.
Real-time Momentum Feedback: Color saturation provides immediate visual feedback on market structure strength, allowing traders to assess levels at a glance without additional indicators.
EMA Ribbon Bands
The 8-level exponential moving average system creates a comprehensive trend structure map with gradient color coding.
Signal Type Visualization
STRATEGY PROPERTIES & BACKTESTING DISCLOSURE
📊 Default Strategy Configuration:
✅ Initial Capital: 100,000 USD (realistic for average traders)
✅ Commission: 0.075% per trade (realistic exchange fees)
✅ Slippage: 3 ticks (market impact consideration)
✅ Position Size: 5% equity per trade (sustainable risk level)
✅ Pyramiding: Disabled (single position management)
✅ Sample Size: 185 trades over 12-month backtesting period
✅ Risk Management: Adaptive stop loss with maximum 1% risk per trade
COMPREHENSIVE BACKTESTING RESULTS
Testing Period & Market Conditions:
Backtesting Period: June 25, 2024 - June 25, 2025 (12 months)
Timeframe: 15-minute charts (MTF system active)
Market: BTCUSDT (Bitcoin/Tether)
Market Conditions: Full market cycle including volatility periods
Deep Backtesting: Enabled for maximum accuracy
📈 Performance Summary:
Total Return: +2.19% (+2,193.59 USDT)
Total Trades Executed: 185 trades
Win Rate: 34.05% (63 winning trades out of 185)
Profit Factor: 1.295 (gross profit ÷ gross loss)
Maximum Drawdown: 0.65% (653.17 USDT)
Risk-Adjusted Returns: Consistent with conservative risk management approach
📊 Detailed Trade Analysis:
Position Distribution:
Long Positions: 109 trades (58.9%) | Win Rate: 36.70%
Short Positions: 76 trades (41.1%) | Win Rate: 30.26%
Average Trade Duration: Optimized for 15-minute timeframe efficiency
Profitability Metrics:
Average Profit per Trade: 11.74 USDT (0.23%)
Average Winning Trade: 151.17 USDT (3.00%)
Average Losing Trade: 60.27 USDT (1.20%)
Win/Loss Ratio: 2.508 (winners are 2.5x larger than losses)
Largest Single Win: 436.02 USDT (8.69%)
Largest Single Loss: 107.41 USDT (controlled risk management)
💰 Financial Performance Breakdown:
Gross Profit: 9,523.93 USDT (9.52% of capital)
Gross Loss: 7,352.48 USDT (7.35% of capital)
Net Profit After Costs: 2,171.44 USDT (2.17%)
Commission Costs: 1,402.47 USDT (realistic trading expenses)
Maximum Equity Run-up: 2,431.66 USDT (2.38%)
⚖️ Risk Management Validation:
Maximum Drawdown: 0.65% showing controlled risk management
Drawdown Recovery: Consistent equity curve progression
Risk per Trade: Successfully maintained below 1.5% per position
Position Sizing: 5% equity allocation proved sustainable throughout testing period
📋 Strategy Performance Characteristics:
✅ Strengths Demonstrated:
Controlled Risk: Maximum drawdown well below industry standards (< 1%)
Positive Expectancy: Win/loss ratio of 2.5+ creates profitable edge
Consistent Performance: Steady equity curve without extreme volatility
Realistic Costs: Includes actual commission and slippage impacts
Sample Size: 185 trades during testing period
⚠️ Performance Considerations:
Win Rate: 34% win rate requires discipline to follow system signals
Market Dependency: Performance may vary significantly in different market conditions
Timeframe Sensitivity: Optimized for 15-minute charts; other timeframes may show different results
Slippage Impact: Real trading conditions may affect actual performance
📊 Benchmark Comparison:
Strategy Return: +2.19% over 12 months
Buy & Hold Bitcoin: +71.12% over same period
Strategy Advantage: Significantly lower drawdown and volatility
Risk-Adjusted Performance: Different risk profile compared to holding cryptocurrency
🎯 Real-World Application Insights:
Expected Trading Frequency:
Average: 15.4 trades per month (185 trades ÷ 12 months)
Weekly Frequency: Approximately 3-4 trades per week
Active Management: Requires regular monitoring during market hours
Capital Requirements:
Minimum Used in Testing: $10,000 for sustainable position sizing
Tested Range: $50,000-$100,000 for comfortable risk management
Commission Impact: 0.075% per trade totaled 1.4% of capital over 12 months
⚠️ IMPORTANT BACKTESTING DISCLAIMERS:
📈 Performance Reality:
Past performance does not guarantee future results. Backtesting results represent hypothetical performance and may not reflect actual trading outcomes due to market changes, execution differences, and emotional factors.
🔄 Market Condition Dependency:
This strategy's performance during the tested period may not be representative of performance in different market conditions, volatility regimes, or trending vs. sideways markets.
💸 Cost Considerations:
Actual trading costs may vary based on broker selection, market conditions, and trade size. Commission rates and slippage assumptions may differ from real-world execution.
🎯 Realistic Expectations:
The 34% win rate requires psychological discipline to continue following signals during losing streaks. Risk management and position sizing are critical for replicating these results.
⚡ Technology Dependencies:
Strategy performance assumes reliable internet connection, platform stability, and timely signal execution. Technical failures may impact actual results.
CONFIGURATION OPTIMIZATION
5-Minute Timeframe Optimization (Advanced Users Only)
⚠️ Important Warning: 5-minute timeframes operate without MTF confirmation, resulting in reduced signal quality and higher false signal rates.
Example 5-Minute Parameters:
Composite Thresholds: Long 6.5, Short 7.0 (vs 15M default 5.0/5.4)
Signal Lookback Bars: 12 (vs 15M default 8)
Volume Multiplier: 2.2 (vs 15M default 1.8)
MTF Timeframe: Disabled (automatic below 30M)
Risk Management Adjustments:
Position Size: Reduce to 3% (vs 5% default)
TP1: 0.8%, TP2: 1.2%, TP3: 2.0% (tighter targets)
SL: 0.8% (tighter stop loss)
Cooldown Minutes: 8 (vs 5 default)
Usage Notes for 5-Minute Trading:
- Wait for higher composite scores before entry
- Require stronger volume confirmation
- Monitor EMA structure more closely
15-Minute Scalping Setup:
TP1: 1.0%, TP2: 1.5%, TP3: 2.5%
Composite Threshold: 5.0 (higher filtering)
TP ATR Multiplier: 7.0
SL ATR Multiplier: 2.5
Volume Multiplier: 1.8 (requires stronger confirmation)
Hold Time: 2 bars minimum
3-Hour Swing Setup:
TP1: 2.0%, TP2: 4.0%, TP3: 8.0%
Composite Threshold: 4.5 (more signals)
TP ATR Multiplier: 8.0
SL ATR Multiplier: 3.2
Volume Multiplier: 1.2
Hold Time: 6 bars minimum
Market-Specific Adjustments
High Volatility Periods:
Increase ATR multipliers (TP: 2.0x, SL: 1.2x)
Raise composite thresholds (+0.5 points)
Reduce position size
Enable cooldown periods
Low Volatility Periods:
Decrease ATR multipliers (TP: 1.2x, SL: 0.8x)
Lower composite thresholds (-0.3 points)
Standard position sizing
Disable extended cooldowns
News Events:
Temporarily disable strategy 30 minutes before major releases
Increase volume requirements (2.0x multiplier)
Reduce position sizes by 50%
Monitor for unusual price action
RISK MANAGEMENT
Dual ROI System: Adaptive vs Fixed Mode
Adaptive RR Mode:
Uses ATR (Average True Range) for automatic adjustment
TP1: 1.0x ATR from entry price
TP2: 1.5x ATR from entry price
TP3: 2.0x ATR from entry price
Stop Loss: 1.0x ATR from entry price
Automatically adjusts to market volatility
Fixed Percentage Mode:
Uses predetermined percentage levels
TP1: 1.0% (default)
TP2: 1.5% (default)
TP3: 2.5% (default)
Stop Loss: 0.9% total (0.6% risk tolerance + 0.3% slippage buffer)(default)
Consistent levels regardless of volatility
Mode Selection: Enable "Use Adaptive RR" for ATR-based targets, disable for fixed percentages. Adaptive mode works better in varying volatility conditions, while fixed mode provides predictable risk/reward ratios.
Stop Loss Management
In Adaptive SL Mode:
Automatically scales with market volatility
Tight stops during low volatility (smaller ATR)
Wider stops during high volatility (larger ATR)
Include 0.3% slippage buffer in both modes
In Fixed Mode:
Consistent percentage-based stops
2% for crypto, 1.5% for forex, 1% for stocks
Manual adjustment needed for different market conditions
Trailing Stop System
Configuration:
Enable Trailing: Activates dynamic stop loss adjustment
Start Trailing %: Profit level to begin trailing (default 1.0%)
Trailing Offset %: Distance from current price (default 0.5%)
Close if Return to Entry: Optional immediate exit if price returns to entry level
Operation: Once position reaches trailing start level, stop loss automatically adjusts upward (longs) or downward (shorts) maintaining the offset distance from favorable price movement.
Timeframe-Specific Risk Considerations
15-Minute and Above (Tested):
✅ Full MTF system active
✅ Standard risk parameters apply
✅ Backtested performance metrics valid
✅ Standard position sizing (5%)
5-Minute Timeframes (Advanced Only):
⚠️ MTF system inactive - local signals only
⚠️ Higher false signal rate expected
⚠️ Reduced position sizing preferred (3%)
⚠️ Tighter stop losses required (0.8% vs 1.2%)
⚠️ Requires parameter optimization
⚠️ Monitor performance closely
1-Minute Timeframes (Limited Testing):
❌ Excessive noise levels
❌ Strategy not optimized for this frequency
Risk Management Practices
Allocate no more than 5% of your total investment portfolio to high-risk trading
Never trade with funds you cannot afford to lose
Thoroughly backtest and validate the strategy with small amounts before full implementation
Always maintain proper risk management and stop-loss settings
IMPORTANT DISCLAIMERS
Performance Disclaimer
Past performance does not guarantee future results. All trading involves substantial risk of loss. This strategy is provided for informational purposes and does not constitute financial advice.
Market Risk
Cryptocurrency and forex markets are highly volatile. Prices can move rapidly against positions, resulting in significant losses. Users should never risk more than they can afford to lose.
Strategy Limitations
This strategy relies on technical analysis and may not perform well during fundamental market shifts, news events, or unprecedented market conditions. No trading strategy can guarantee 100% success or eliminate the risk of loss.
Legal Compliance
You are responsible for compliance with all applicable regulations and laws in your jurisdiction. Consult with licensed financial professionals when necessary.
User Responsibility
Users are responsible for their own trading decisions, risk management, and compliance with applicable regulations in their jurisdiction.
(XSN7) with SMT Divergence v9.0 The (XSN7) is an efficiency and precision tool designed for traders who operate with a time-based, multi-market methodology. Its primary purpose is to automate the most time-consuming aspects of liquidity and SMT analysis, allowing the trader to focus on execution rather than manual chart preparation.
Why This Tool Provides a Unique Edge
Many indicators can show sessions or require manual SMT setup. This tool is fundamentally different by solving two critical workflow problems:
It Automates High/Low Tracking: You no longer need to manually draw lines on the highs and lows of every 1-Hour, 4-Hour, or 15-Minute candle you want to track. The script does this for you automatically, tracking the exact high/low of every completed session across your chart history. This not only saves a significant amount of time but also ensures 100% precision and consistency, removing the risk of human error in your analysis.
It Automates SMT Analysis with a 'One-Time Setup': Analyzing SMT divergence traditionally requires manually switching between charts and constantly changing the input for your correlated symbol. Our SMT Auto-Pairing Engine eliminates this entirely. You configure your primary trading pairs (e.g., NQ/ES, EURUSD/DXY) one time. The script then intelligently detects which asset you are viewing and automatically pulls data from its correct correlated pair—with the correct inverse logic if needed. This creates a seamless, streamlined workflow for multi-market analysis.
By automating these core processes, the indicator provides a tangible edge in speed and accuracy.
Key Features
Automated High/Low Tracking: The script automatically identifies, marks, and tracks the precise high and low of completed 1-Hour, 4-Hour, 90-Minute, and 15-Minute sessions.
Intelligent Liquidity Sweep Alerts: Receive real-time alerts the moment an automatically-tracked session high or low is swept. Alerts are highly configurable, with filters for Daily Bias (Bullish/Bearish) and specific hours of the day.
'One-Time Setup' SMT Auto-Pairing Engine: Define your correlated pairs once, and the script handles the rest. It automatically detects your active chart and applies the correct SMT analysis without needing any further manual input.
Full Visual & Technical Control: Customize every visual element, including session colors, line styles, and labels. Includes Light/Dark themes and precise timezone settings to match your trading environment.
How to Use This Indicator
1. Setup & Configuration:
Timezone: In the ⚙️ General Settings, set your UTC (+/-) offset to align the session boxes with your local time.
SMT Auto-Pairing (One-Time Setup):
Go to the ⚙️ SMT Auto-Pairing settings.
Check Enable SMT Auto-Pairing.
For each pair you trade, define the Primary ticker (the one on your chart) and the Correlated ticker. Be sure to check Inverse if required (e.g., EURUSD vs. DXY).
This system now works automatically in the background.
2. Alert Configuration:
Click the "Alert" button in TradingView.
Set "Condition" to the script name: (XSN7) with SMT Divergence....
Select "Any alert() function call" and set the frequency to "Once Per Bar".
In the script's 🚨 Alert & Sweeper Settings, check the boxes for the hours (NY Time) during which you want to receive sweep alerts.
AQPRO ScalperX📝 INTRODUCTION
AQPRO ScalperX is a trading indicator designed for fast-paced, intraday trading. It uses Donchian channel breakouts, combined with a proprietary filtering system, to catch buy and sell opportunities as close to the beginning as possible without losing quality of the signals.
On top of core signals, ScalperX includes a real-time max profit tracker, a multi-timeframe (MTF) dashboard, support and resistance zones, and risk management visualization tools like automatic rendering of TP and SL lines. The indicator is fully customizable for both its visuals and functional settings.
🎯 PURPOSE OF USAGE
This indicator was initially designed with the idea of trying to make such a tool, that would be able to catch trend reversal in the most safe way. In this particular situation term 'safe way' is very abstract and it is up to interpretation, but we decided that our definition will be 'trading with price breakouts' , meaning that we would like to capitalize on price breaking its previous structure in the direction opposite to the previous one.
You can clearly see on the chart how buy and sell signals are going one after another on the screenshot below:
This ensures that we follow trend consistently and without missing out on potential profits. Just like they say: " let the winners run ".
Even though indicator with similar goals already exist in the open market, we believe that our proprietary algorithms and filters for determining price breakouts can make a big difference to traders, which employ similar strategies on daily basis, by helping them understand where are the potential high-quality breakouts might be. We haven't found indicator with exact same functionality as ours, which means that traders will be able to leverage an actually new tool to generate new price insights.
In short, main goals of this indicator are as follows:
Catching high-quality price breakouts, filtered to reduce the amount of choppy moves and false signals;
Tracking potential profits in real-time, directly on trader's chart;
Organizing data visualization of data pf latest signals from chosen asset from multiple timeframe in one dashboard;
Automated highlighting of key support and resistance zones on the chart, which serve as confirmation for main signals;
⚙️ SETTINGS OVERVIEW
Options for customization of this indicator are straightforward, but let's review them to make things certainly clear:
🔑 ScalperX / Main Settings
Range — defines the "wideness" of the breakout boxes. Higher values create wider breakout zones and impact breakout sensitivity;
Filter — adjusts the spacing between breakout boxes, determining the strictness of signal filtering. Higher values lead to more selective and rarer signals;
Show Max Profit — displays a real-time line and label that updates when a trade achieves a new peak profit, measured in ticks.
⏰ MTF Signal / Main Settings
Show MTF Signals — enables the generation of buy/sell signals from selected higher timeframes, displayed as labels on the current chart;
Timeframe — specifies the higher timeframe to use for MTF signal detection, such as 1 hour (1h) or 4 hours (4h).
🗂️ MTF Dashboard / Main Settings
Show MTF Dashboard — activates a dashboard that tracks entries, TP, SL, and overall trade bias for one selected symbol across four customizable timeframes;
* Dashboard position ( Vertical ) — adjusts whether the dashboard appears on the Top, Middle, or Bottom of the chart;
* Dashboard position ( Horizontal ) — aligns the dashboard Left, Center, or Right within the chart window;
* the name of the parameter is hidden in the settings
🗂️ MTF Dashboard / Ticker
Ticker to Track — Allows you to choose the specific ticker symbol (e.g., BINANCE:BTCUSDT) for MTF tracking.
🗂️ MTF Dashboard / Timeframes
* Timeframe 1 — set the first timeframe for multi-timeframe analysis (e.g., 15 minutes);
* Timeframe 2 — set the second timeframe for multi-timeframe analysis (e.g., 30 minutes);
* Timeframe 3 — set the third timeframe for multi-timeframe analysis (e.g., 1 hour);
* Timeframe 4 — set the fourth timeframe for multi-timeframe analysis (e.g., 4 hours).
* the name of the parameter is hidden in the settings
🛡️ Risk Management / Main Settings
Show TP&SL — displays dynamic lines and labels for the entry, Take Profit (TP), and Stop Loss (SL) of the most recent signal, updated in real-time until a new signal triggers;
Risk-to-Reward Ratio (R:R) — defines the ratio for TP and SL calculation to control your risk and reward on every trade.
📐 Support & Resistance / Main Settings
Show Support & Resistance Zones — enables dynamic zones based on pivot points, colored bullish or bearish based on price context;
History Lookback — defines the number of bars to consider when calculating support and resistance levels. Increasing this results in zones derived from longer-term price structures.
🎨 Visual Settings / ScalperX
Bullish Box — defines the color for bullish breakout boxes;
Bearish Box — defines the color for bearish breakout boxes;
Max Profit — sets the color for the max profit line on the chart.
🎨 Visual Settings / S&R
Support — defines color used for standard support zones;
Resistance — defines color used for standard resistance zones;
Strong Support — defines special color for zones classified as "strong support";
Strong Resistance — defines special color for zones classified as "strong resistance".
🎨 Visual Settings / MTF Dashboard
Bullish — sets the color for bullish trade states in the MTF dashboard;
Bearish — sets the color for bearish trade states in the MTF dashboard.
🔔 Alerts / Main Settings
Buy & Sell — toggles alerts for buy and sell signals detected by the indicator in the current chart timeframe;
MTF Buy & Sell — toggles alerts for buy and sell signals detected across the selected MTF timeframes.
📈 APPLICATION GUIDE
Application flow of this indicator very easy to understand and get used to, because all of the necessary elements — analysis, drawing, alert — are already automated by our algorithms. Let's review how the indicator works.
Let's start with the most basic thing — how will your indicator look when you load it on your chart for the first time:
AQPRO ScalperX consists mainly of 6 logic blocks:
ScalperX signals;
Risk visualization;
Max Profit tracking;
MTF scalper signals;
MTF dashboard;
Support & Resistance zones.
Description of each logic block is provided in the corresponding sections below.
SCALPERX SIGNALS
Signals, generated by our indicator, are shown on the chart as coloured up/down triangle. When a signal appears on the chart, indicator also create a box of length equal to 'Range' parameter from "Main Settings" group of settings. This box is intended to show which area of the price was broken by current candle.
It also important to acknowledge, the breakout itself happens only when price closes beyond broken price area with its close (!) price . Breakouts with highs or lows are not counted. This reduces the amount of low-quality signals and ensures that only the strong breakout will appear on the chart.
VERY IMPORTANT NOTE: all signals are considered valid only on the close of the candle, which triggered the signal, so if you want to enter a trade by any signal, wait for its candle to close and open your trade right on the next candle.
Talking about scalper's settings, we need to shed a light on how the changes in them affect signal's quality.
Parameter 'Range' defines the amount of bars, that will be review prior to current candle to determine wether the price area of this bars is good enough to track and if current candle actually broke this price area.
👍 Rule of thumb : the higher the 'Range' is, the "wider" the boxes. Also the with the increase of this parameter rises the lag of the signals, so be carefully with setting high values to this parameter.
See the visual showcase of signals with different 'Range' parameters on the screenshot below:
The example above features two instancies of ScalperX with two different 'Range' parameter values: 15 (leftchart) and 5 (right chart). You can clearly see, that on left chart here are 2 signals in comparison to 6 signals on right chart. Also signals on the left side have bigger lag and they don't catch the start of the move in comparison to how quickly tops and bottoms are catched with low 'Range' . However, low 'Range' will lead to excessive amount of signals, quality of which during 'whipsaw' markets is not that great.
✉️ Our advice on how to optimally set 'Range' parameter:
Use low values to trade during the times, when there are a lot of clean up and down impulses. This way you will catch reversal opportunities sooner and the quality of the signals will still be great;
Use high values on the 'whipsaw' markets. This will filter out many bad signals, that you would get with low-value 'Range' , and will drastically reduces amount of losing trades.
Talking about the 'Filter' parameter, this particular setting defines the 'strictness' of rules which will be applied to price area validation process. Essentially, the higher this parameter is, the stronger price impulse has to be confirm the breakout. However, changes in this parameter will not impact the "wideness" of boxes at all.
👍 Rule of thumb : the higher the 'Filter' is, the more separated the signal will be. Setting this parameter to high value will lead to increase in lag and big reduction in amount of signals, so be careful this parameter to high values.
See the visual showcase of signals with different 'Filter' parameters on the screenshot below:
The example above features two instancies of ScalperX with two different 'Filter' parameter values: 20 (left chart) and 2.5 (right chart). You can clear see, that low 'Filter' generated 6 signals, while higher one generated only 4 signals. However if you look closer, you will see that 2 signals, that existing in the yellow dashed area on the right chart, don't exist in the same area on the left chart. This is because high value of this parameter requires price impulse to be very strong in order for the indicator to mark this breakout as a valid one. What is more important is that these 2 'missing' signals were actually bad and, technically, we actually cut our losses in this case with high value of 'Filter' . You can see that the leftmost sell signal on the left chart eventually closed in a nice profit, in comparison to the same trade being closed in a loss on the right chart because of the 2 signals that we were talking about above.
It is important to note, that setting 'Filter' to low values will not affect performance this much as it low value of 'Range' do, because the indicator already works on low values of this parameter by default and the signals on average are already good enough for trading.
✉️ Our advice on how to optimally set 'Filter' parameter:
Use low values to trade on the markets with clean up and down impulses. This way you avoid excessive filtering and leave a room for good signals to come right at you;
Use high values to trade on 'whipsaw' markets. Higher values of this parameter on these markets have same effect as high 'Range' parameter: filtering false signals and leaving room for actually strong price impulses, which you will later capitalize on.
RISK VISUALIZATION (TP&SL)
Rendering Take-Profits and Stop-Losses in our indicator works quite simple: for each new trade indicator creates new pairs of lines and labels for TP and SL, while lines & labels from previous trade are erased for aesthetics purposes. Each label shows price coordinates, so that each trader would be able to grap the numbers in seconds.
See the visual showcase of TP & SL visualization on the screenshot below:
Also, whenever TP or SL of the current trade is reached, drawing of both TP and SL stops. When the TP is reached, additional '✅' emoji on the TP price is shown as confirmation of Take-Profit.
However, while TP or SL has not been reached, TP&SL labels and lines will be prolonged until one of them will be reached or new signals will come.
See the visual showcase of TP & SL stopping being visualized & TP on the screenshot below:
MAX PROFIT TRACKING
This mechanic is not particularly a new one in field of trading, but people usually forgot that it can be a useful indicator of state of the market:
when lines and labels of Max Profit are far from entry points on consistent basis , it usually means that indicator's signals actually can catch a beginning of good price moves, which enables trader to capitalize on them;
when lines and labels of Max Profit are close to entry points on consistent basis , it means that either market is choppy or the indicator can't catch trading opportunities in time. To 'fix' this you can try to reconfigure scalper's parameters, which were described above.
Principles of Max Profit in this indicator are of industry-standard: when price updates its extremum and 'generates' more profit than it previously did, Max Profit label and line change their position to this extremum. Max Profit label displays the maximum potential amount of profit that a trader could have got during this trade in pips (!) .
See the visual showcase of Max Profit work on the screenshot below:
MTF SCALPER SIGNALS
The principles of these signals are exactly the same as principles for classic Scalper signals. Refer to 'Scalper Signals' section above to rehearse the knowledge.
Logic behind these signals is very simple:
We take classic Scalper signals;
We request the data about these latest signals from specific other timeframe ( user can choose it in the settings );
If such signals appeared, we display it on the chart as a big label with timeframe value inside of it. In comparison to classic signals, no additional boxes are created . TP&SL functionality doesn't cover MTF signals, so don't expect to see TP&SL lines and labels for MTF signals.
See the visual showcase of MTF Scalper signals on the screenshot below:
MTF DASHBOARD
The functionality of the dashboard is pretty simple, but it makes the dashboard itself a very powerful tool in a hands of experienced trader.
Let's review structure of MTF dashboard on the screenshot below:
The important feature of MTF dashboard is that its tracks latest trade's data from a particular ticker and its four timeframes, all of which any trader chooses in the settings. This means, that you can be on asset ABC , but track the data from asset XYZ . This allows for a quick scan of sentiment from different assets and their timeframes, which gives traders a clue on what is the trend on these assets both on lower and higher timeframes at the same moment and saves a lot of time from jumping from one asset & timeframe to another.
To see that this is exactly the case with our indicator, see the screenshot below:
Needless to say, that you can track current asset in the dashboard as well. This will have the same benefits, described in the paragraph above.
You can also customize colours for bullish and bearish patterns for MTF Dashboard in the settings.
SUPPORT & RESISTANCE ZONES
Support & resistance (S&R) zones are a great tool for confirming Scalper signals in complex situations. Using these zones to determine whether or a particular entry opportunity is good is a practice of professional traders, which we specifically added to our indicator for the reason of improving the quality of Scalper signals in long run.
The mechanics behind these zones is based on pivot points, the lookback for which you can customize in the parameter called 'History Lookback (Bars)' in "Support & Resistance / Main Settings" group of settings. Increasing this parameter will lead to a appearance of more 'global' zones, but they will appear much rarer, rather then zones, generated with low values of this parameter.
The quality of these zones doesn't change much when changing this parameter — it only changes the frequency of the zones on the chart. Zones, generated from high values of this parameter are more suitable for long-term trading, while zones, generated from low value of this parameter, are more suitable for short-term trading.
It also important to mention that any zone on the chart is considered active only until the moment its farther border ( top border for resistance zones and bottom border for support zones) is reached by price's high or low .
Take a look on the screenshot below to see which zones does the indicator draw:
Let's review the zones themselves now:
Classic Support/Resistance Zone — a standard zone, which on average has amedium success rate to reverse the price when collided with it;
High-buyer-volume/High-seller-volume Support/Resistance Zone — a stronger zone, which on average has much better success rate to reverse the price when collided with it. Classic zone is marked as high-volume only if the up/down volume near the pivot point of this zone is greater than a certain threshold ( not changeable );
Extreme Support/Resistance Zone — a zone, which appeared beyond price's least-possible-to-cross levels, and has to the highest success rate of reversing the price on encounter across the zones, mentioned previously. Classic zone, which appeared beyond certain price levels, calculated with our proprietary risk system, is considered extreme. Classic zone doesn't need to be high-volume to become an Extreme Zone!
High-buyer-volume/High-seller-volume Extreme Support/Resistance Zone — an Extreme Zone, which has also passed up/down volume evolution process, mentioned in the point 2 .
Trading with the zones, mentioned above, with highest-on-paper success rate — especially Extreme Zones — does NOT guarantee you a price reversal when the price will reach this zone. However, by conducting our own extensive research with this indicator, we have found that using these zone will actually help you increase your success rate on average, because using these zones as confirmation systems filter out quite a number of false signals on average.
It is also important to mention, that opacity (same as 'transparency') of S&R zones depends on the volume of around zone's pivot point:
if volume is high , zone has 'brighter' (less opacity) colour;
if volume is low , zone has 'darker' (more opacity) colour.
Let's review examples of Scalper signal, which 1) where filtered out by our S&R zones and 2) where confirmed by our S&R zones. See the screenshot below:
The example above clearly shows the importance of having an S&R zone confirming the signal. This kind of 'team work' between of Scalper signals and S&R zones results in filtering lots of bad signals and confirmation of truly strong ones.
🔔 ALERTS
This indicator employs alerts for an event when new signal occurs on the current timeframe or on MTF timeframe. While creating the alert below 'Condition' field choose 'any alert() function call'.
When this alert is triggered, it will generate this kind of message:
// Alerts for current timeframe
string msg_template = "EXCHANGE:ASSET, TIMEFRAME: BUY_OR_SELL"
string msg_example = "BINANCE:BTCUSDT, 15m: Buy"
// Alerts for MTF timeframe
string msg_template_mtf = "MTF / EXCHANGE:ASSET, TIMEFRAME: BUY_OR_SELL"
string msg_example_mtf = "MTF / BINANCE:BTCUSDT, 1h: Buy"
📌 NOTES
This indicators works best on assets with high liquidity; most suitable timeframes range from 1m to 4h (depends on your trading style) ;
Seriously consider using S&R zones as confirmation to main Scalper signals or any of your own signals. Confirmation process may filter out a lot of signals, but your PNL History will say "thank you" to you in the long-run and you will see yourself how good confirmed signals actually do work;
Don't forget to look at MTF dashboard from time to time to see global sentiment. This will help you time your entry moments better and will improve your performance in the long run;
This indicator can serve both as primary source of signals and as confirmation tool, but we advise to try to combine it with your own strategy frst to see if it will improve your performance.
🏁 AFTERWORD
AQPRO ScalperX was designed to help traders identify high-quality price breakouts and generate market insights based on them, which include signal generation. Main feature of this indicator is Scalper algorithm, which generate price-breakout-based signals directly on your chart.
Alongside these signals you can leverage 1) MTF Dashboard to track latest trade's data from chosen asset and its four timeframes, 2) risk visualization functionality (TP&SL) to improve understanding of current market risks and 3) Support & Resistance zones, which serve as a great confirmation tool for Scalper signals, but can also work with any other signal generation tool to enhance its performance.
ℹ️ If you have questions about this or any other our indicator, please leave it in the comments.
ReversoReverso – Moving Average Touch Statistics Tracker
Reverso indicator is a technical analysis tool that tracks and visualizes how price interacts with a selected Exponential Moving Average (EMA). It provides detailed statistics about price behavior before, during, and after each EMA touch event.
This script is suitable for both trend-following and mean-reversion traders who want to study EMA reactions, understand market tendencies, and refine entry/exit strategies based on price-memory dynamics.
Features and Functionality
Supported MAs: EMA 9, 20, or 50
Timeframe Support: Uses the chart’s timeframe
Touch Detection: Triggered when the price range (high to low) crosses or touches the EMA
Automatic Data Tracking
Tables for Quick Visual Summary
Visual Overlay: Optional EMA line plotted on chart
Timeframe Support: Uses the chart’s timeframe
Capped history: Most recent 50 touches
Automatic Data Tracking:
Number of EMA touches
Time intervals between touches
Price distance from last touch
Maximum price deviation (above/below EMA) between touches
Time spent above/below EMA
Tables for Quick Visual Summary:
Info Table: Live details about last and first touches, distance from touch, bars above/below, peak movements since last touch
Stats Table: Averages and extreme values for price behavior patterns across recent history
Core Metrics Tracked
Last Touch Price: The last price level where price touched the EMA
Distance from Last Touch: Current % change from the last touch price
Time Between Touches: Average and maximum intervals (in bars or time) between touch events
Max Distance Above/Below: Peak movement above/below EMA between touches
Bars Above/Below: How long price stayed above/below the EMA since last touch
Peak This Cycle: Max deviation above/below in current cycle since last touch
How It Works
Reverso monitors each bar to check if price intersects the selected EMA.
When a new touch occurs, it records the touch price and time, and resets the tracking cycle.
From that point forward, it tracks how far and how long price drifts above or below the EMA.
This process repeats with each new touch, building a detailed profile of how price behaves around the moving average.
The result is a visual and statistical framework for understanding price memory, market rhythm, and mean-reversion opportunities.
Customization Options
EMA Length: Choose from EMA 9, 20, or 50
Show MA Line: Toggle the EMA plot on the chart
Show Info Table: Enable/disable the current-touch summary
Show Statistics Table: Show aggregate data over the history
Table Positioning: Customizable placement for both tables
MA Color: Select custom color for EMA plot
Intended Use Cases
Identify reversal or continuation setups near EMAs
Validate strategies relying on mean reversion
Backtest the consistency of price respect to EMAs
Detect periods of volatility clustering around EMAs
Notes and Disclaimers
This script does not repaint: calculations are made on confirmed bars.
This indicator is educational in nature and should be used alongside other forms of analysis.
Time durations in the tables are approximated using bar timing and may vary across markets/timeframes.
Momentum Pull Back Stratergy"Master Pull Back Strategy" is a highly detailed momentum and volume-based trading system designed for Trading View. It visually annotates the chart, detects buy/sell signals, tracks market phases, and evaluates retracements and confirmations. Below is a full breakdown of its logic and components:
🔷 1. Volume Profile Highlights (Arrow Emojis)
Purpose: Show volume strength vs. average using color-coded arrows.
Calculates average volume over a user-defined period (length = 10).
Divides current volume by average volume to get volRatio.
Based on volRatio, plots small arrows (acting like diamonds) in various colors:
Low volume (black, navy, blue...) to high volume (yellow, red, purple).
Visual Purpose: Give a quick sense of how "loud" or "quiet" a candle's volume is.
📈 2. Highs of Day Tracking
Purpose: Track the high price reached during different trading sessions.
Defines pre-market, regular, and post-market sessions.
Tracks the highest price (high) in each session.
Plots colored lines:
Orange: Pre-market high
Red: Regular market high
Blue: Post-market high
🟩 3. Green Candle Pattern Detection
Purpose: Detect bullish patterns formed by consecutive green candles.
Key Conditions:
Count green candles (greenCount) until a red candle appears or 10 candles max.
Require at least 1 silver-or-above volume candle (volRatio >= 1.0).
Must have ≥3% price gain during the green sequence.
Must accumulate >20,000 volume during the green run.
If Valid:
Locks the pattern.
Records important values:
patternStartPrice, patternEndPrice, totalPatternVolume, patternHigh, patternBars
Marks the bar after which red starts (redStartBar)
⬇️ 4. Retracement Monitoring
Purpose: Track retracement from the pattern high after it locks.
Defines retracement percentage:
(greenPatternHigh - low) / (greenPatternHigh - greenPatternLow)
If retracement exceeds 80%, it invalidates the pattern.
Buy signal is disabled if pattern retraces too far.
✅ 5. Buy Signal Logic
Purpose: Fire a buy signal after pattern lock if price breaks above local high.
Conditions:
Pattern is locked (patternLocked).
Price breaks above a short-term high (triggerBreak).
It's not the first red candle.
Price is within 8.5% above EMA9.
Buy signal fires and:
Sets buyActive = true
Tracks highest price after buy
Stores buyPrice = close
❌ 6. Sell Signal Logic
Purpose: Exit signal after retracement from post-buy high.
While buy is active:
If price retraces ≥3% from the post-buy high → sellSignal = true
Resets buyActive, trackedHigh, and buyPrice
Plots a red "SELL" label above the bar.
🎨 7. Buy Signal Visual Color Coding
Purpose: Color buy signal based on how deep the retracement is.
Uses retracement percentage:
≥65% → Red (high risk)
45–65% + MACD bullish → Yellow (moderate)
<45% + MACD bullish → Green (ideal)
Plots BUY label below bar in the respective color.
🔻 8. Retracement Triangle Visuals
Purpose: Shows retracement progression while pattern is locked.
If pattern is locked and not ready for buy:
Plots triangle below bar in the buyColor for visual tracking.
⭐ 9. Star Markers Above Lock Candle
Purpose: Confirmations when pattern locks.
First Star:
Plotted above the first red candle after green pattern lock.
Second Star (⭐⭐):
Additional confirmations:
Volume OK (less than previous)
MACD bullish
Price > VWAP
VolAtLock > 100K
Price up >6% from first green candle
Price below 75% of daily EMA200 or above EMA200
Third Star (⭐⭐⭐):
Even stricter confirmations:
Volume < 60% of previous
High <= previous high
VolAtLock > 500K
Price > $3
Gain >9% from first green
Price < 50% of daily EMA200 or above EMA200
📊 10. Bar Coloring
Purpose: Visually highlight bars based on pattern phase and MACD.
Gray: MACD Bearish
Light Green: Part of active green pattern
Blue: In locked phase but no buy triggered
🔄 11. Reset Logic
Purpose: Clears all tracking variables once a buy signal fires or pattern is invalidated.
Also resets if:
Retracement is too deep
10 candles pass post-lock without a trigger
⛰️ 12. Double Top Detection
Purpose: Basic visual marker when current high == previous high.
Plots a gray triangle if current and previous bar highs match.
📌 Summary: What This Strategy Shows
Buy Opportunities: Based on high-volume green runs and confirmed breakouts.
Sell Triggers: Once a retracement from peak exceeds 3%.
Visuals for Confirmation:
Diamonds for volume
Stars for lock confidence
Colors for retracement strength
Risk Management:
Retracement filtering
Time limits on locked phases
Volume filters
Market Context: Tracks pre/regular/post market highs and daily EMA 200.
taLibrary "ta"
█ OVERVIEW
This library holds technical analysis functions calculating values for which no Pine built-in exists.
Look first. Then leap.
█ FUNCTIONS
cagr(entryTime, entryPrice, exitTime, exitPrice)
It calculates the "Compound Annual Growth Rate" between two points in time. The CAGR is a notional, annualized growth rate that assumes all profits are reinvested. It only takes into account the prices of the two end points — not drawdowns, so it does not calculate risk. It can be used as a yardstick to compare the performance of two instruments. Because it annualizes values, the function requires a minimum of one day between the two end points (annualizing returns over smaller periods of times doesn't produce very meaningful figures).
Parameters:
entryTime : The starting timestamp.
entryPrice : The starting point's price.
exitTime : The ending timestamp.
exitPrice : The ending point's price.
Returns: CAGR in % (50 is 50%). Returns `na` if there is not >=1D between `entryTime` and `exitTime`, or until the two time points have not been reached by the script.
█ v2, Mar. 8, 2022
Added functions `allTimeHigh()` and `allTimeLow()` to find the highest or lowest value of a source from the first historical bar to the current bar. These functions will not look ahead; they will only return new highs/lows on the bar where they occur.
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `high`.
Returns: (float) The highest value tracked.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
Parameters:
src : (series int/float) Series to track. Optional. The default is `low`.
Returns: (float) The lowest value tracked.
█ v3, Sept. 27, 2022
This version includes the following new functions:
aroon(length)
Calculates the values of the Aroon indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the Aroon-Up and Aroon-Down values.
coppock(source, longLength, shortLength, smoothLength)
Calculates the value of the Coppock Curve indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
longLength (simple int) : (simple int) Number of bars for the fast ROC value (length).
shortLength (simple int) : (simple int) Number of bars for the slow ROC value (length).
smoothLength (simple int) : (simple int) Number of bars for the weigted moving average value (length).
Returns: (float) The oscillator value.
dema(source, length)
Calculates the value of the Double Exponential Moving Average (DEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `source`.
dema2(src, length)
An alternate Double Exponential Moving Average (Dema) function to `dema()`, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The double exponentially weighted moving average of the `src`.
dm(length)
Calculates the value of the "Demarker" indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
ema2(src, length)
An alternate ema function to the `ta.ema()` built-in, which allows a "series float" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int/float) Number of bars (length).
Returns: (float) The exponentially weighted moving average of the `src`.
eom(length, div)
Calculates the value of the Ease of Movement indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
div (simple int) : (simple int) Divisor used for normalzing values. Optional. The default is 10000.
Returns: (float) The oscillator value.
frama(source, length)
The Fractal Adaptive Moving Average (FRAMA), developed by John Ehlers, is an adaptive moving average that dynamically adjusts its lookback period based on fractal geometry.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The fractal adaptive moving average of the `source`.
ft(source, length)
Calculates the value of the Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
ht(source)
Calculates the value of the Hilbert Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
ichimoku(conLength, baseLength, senkouLength)
Calculates values of the Ichimoku Cloud indicator, including tenkan, kijun, senkouSpan1, senkouSpan2, and chikou. NOTE: offsets forward or backward can be done using the `offset` argument in `plot()`.
Parameters:
conLength (int) : (series int) Length for the Conversion Line (Tenkan). The default is 9 periods, which returns the mid-point of the 9 period Donchian Channel.
baseLength (int) : (series int) Length for the Base Line (Kijun-sen). The default is 26 periods, which returns the mid-point of the 26 period Donchian Channel.
senkouLength (int) : (series int) Length for the Senkou Span 2 (Leading Span B). The default is 52 periods, which returns the mid-point of the 52 period Donchian Channel.
Returns: ( [float, float, float, float, float ]) A tuple of the Tenkan, Kijun, Senkou Span 1, Senkou Span 2, and Chikou Span values. NOTE: by default, the senkouSpan1 and senkouSpan2 should be plotted 26 periods in the future, and the Chikou Span plotted 26 days in the past.
ift(source)
Calculates the value of the Inverse Fisher Transform indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
Returns: (float) The oscillator value.
kvo(fastLen, slowLen, trigLen)
Calculates the values of the Klinger Volume Oscillator.
Parameters:
fastLen (simple int) : (simple int) Length for the fast moving average smoothing parameter calculation.
slowLen (simple int) : (simple int) Length for the slow moving average smoothing parameter calculation.
trigLen (simple int) : (simple int) Length for the trigger moving average smoothing parameter calculation.
Returns: ( [float, float ]) A tuple of the KVO value, and the trigger value.
pzo(length)
Calculates the value of the Price Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
rms(source, length)
Calculates the Root Mean Square of the `source` over the `length`.
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The RMS value.
rwi(length)
Calculates the values of the Random Walk Index.
Parameters:
length (simple int) : (simple int) Lookback and ATR smoothing parameter length.
Returns: ( [float, float ]) A tuple of the `rwiHigh` and `rwiLow` values.
stc(source, fast, slow, cycle, d1, d2)
Calculates the value of the Schaff Trend Cycle indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
fast (simple int) : (simple int) Length for the MACD fast smoothing parameter calculation.
slow (simple int) : (simple int) Length for the MACD slow smoothing parameter calculation.
cycle (simple int) : (simple int) Number of bars for the Stochastic values (length).
d1 (simple int) : (simple int) Length for the initial %D smoothing parameter calculation.
d2 (simple int) : (simple int) Length for the final %D smoothing parameter calculation.
Returns: (float) The oscillator value.
stochFull(periodK, smoothK, periodD)
Calculates the %K and %D values of the Full Stochastic indicator.
Parameters:
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
stochRsi(lengthRsi, periodK, smoothK, periodD, source)
Calculates the %K and %D values of the Stochastic RSI indicator.
Parameters:
lengthRsi (simple int) : (simple int) Length for the RSI smoothing parameter calculation.
periodK (simple int) : (simple int) Number of bars for Stochastic calculation. (length).
smoothK (simple int) : (simple int) Number of bars for smoothing of the %K value (length).
periodD (simple int) : (simple int) Number of bars for smoothing of the %D value (length).
source (float) : (series int/float) Series of values to process. Optional. The default is `close`.
Returns: ( [float, float ]) A tuple of the slow %K and the %D moving average values.
supertrend(factor, atrLength, wicks)
Calculates the values of the SuperTrend indicator with the ability to take candle wicks into account, rather than only the closing price.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is false.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
szo(source, length)
Calculates the value of the Sentiment Zone Oscillator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
t3(source, length, vf)
Calculates the value of the Tilson Moving Average (T3).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
t3Alt(source, length, vf)
An alternate Tilson Moving Average (T3) function to `t3()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
vf (simple float) : (simple float) Volume factor. Affects the responsiveness.
Returns: (float) The Tilson moving average of the `source`.
tema(source, length)
Calculates the value of the Triple Exponential Moving Average (TEMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
tema2(source, length)
An alternate Triple Exponential Moving Average (TEMA) function to `tema()`, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The triple exponentially weighted moving average of the `source`.
trima(source, length)
Calculates the value of the Triangular Moving Average (TRIMA).
Parameters:
source (float) : (series int/float) Series of values to process.
length (int) : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `source`.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a "series int" length argument.
Parameters:
src : (series int/float) Series of values to process.
length : (series int) Number of bars (length).
Returns: (float) The triangular moving average of the `src`.
trix(source, length, signalLength, exponential)
Calculates the values of the TRIX indicator.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Length for the smoothing parameter calculation.
signalLength (simple int) : (simple int) Length for smoothing the signal line.
exponential (simple bool) : (simple bool) Condition to determine whether exponential or simple smoothing is used. Optional. The default is `true` (exponential smoothing).
Returns: ( [float, float, float ]) A tuple of the TRIX value, the signal value, and the histogram.
uo(fastLen, midLen, slowLen)
Calculates the value of the Ultimate Oscillator.
Parameters:
fastLen (simple int) : (series int) Number of bars for the fast smoothing average (length).
midLen (simple int) : (series int) Number of bars for the middle smoothing average (length).
slowLen (simple int) : (series int) Number of bars for the slow smoothing average (length).
Returns: (float) The oscillator value.
vhf(source, length)
Calculates the value of the Vertical Horizontal Filter.
Parameters:
source (float) : (series int/float) Series of values to process.
length (simple int) : (simple int) Number of bars (length).
Returns: (float) The oscillator value.
vi(length)
Calculates the values of the Vortex Indicator.
Parameters:
length (simple int) : (simple int) Number of bars (length).
Returns: ( [float, float ]) A tuple of the viPlus and viMinus values.
vzo(length)
Calculates the value of the Volume Zone Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
williamsFractal(period)
Detects Williams Fractals.
Parameters:
period (int) : (series int) Number of bars (length).
Returns: ( [bool, bool ]) A tuple of an up fractal and down fractal. Variables are true when detected.
wpo(length)
Calculates the value of the Wave Period Oscillator.
Parameters:
length (simple int) : (simple int) Length for the smoothing parameter calculation.
Returns: (float) The oscillator value.
█ v7, Nov. 2, 2023
This version includes the following new and updated functions:
atr2(length)
An alternate ATR function to the `ta.atr()` built-in, which allows a "series float" `length` argument.
Parameters:
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The ATR value.
changePercent(newValue, oldValue)
Calculates the percentage difference between two distinct values.
Parameters:
newValue (float) : (series int/float) The current value.
oldValue (float) : (series int/float) The previous value.
Returns: (float) The percentage change from the `oldValue` to the `newValue`.
donchian(length)
Calculates the values of a Donchian Channel using `high` and `low` over a given `length`.
Parameters:
length (int) : (series int) Number of bars (length).
Returns: ( [float, float, float ]) A tuple containing the channel high, low, and median, respectively.
highestSince(cond, source)
Tracks the highest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the highest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `high`.
Returns: (float) The highest `source` value since the last time the `cond` was `true`.
lowestSince(cond, source)
Tracks the lowest value of a series since the last occurrence of a condition.
Parameters:
cond (bool) : (series bool) A condition which, when `true`, resets the tracking of the lowest `source`.
source (float) : (series int/float) Series of values to process. Optional. The default is `low`.
Returns: (float) The lowest `source` value since the last time the `cond` was `true`.
relativeVolume(length, anchorTimeframe, isCumulative, adjustRealtime)
Calculates the volume since the last change in the time value from the `anchorTimeframe`, the historical average volume using bars from past periods that have the same relative time offset as the current bar from the start of its period, and the ratio of these volumes. The volume values are cumulative by default, but can be adjusted to non-accumulated with the `isCumulative` parameter.
Parameters:
length (simple int) : (simple int) The number of periods to use for the historical average calculation.
anchorTimeframe (simple string) : (simple string) The anchor timeframe used in the calculation. Optional. Default is "D".
isCumulative (simple bool) : (simple bool) If `true`, the volume values will be accumulated since the start of the last `anchorTimeframe`. If `false`, values will be used without accumulation. Optional. The default is `true`.
adjustRealtime (simple bool) : (simple bool) If `true`, estimates the cumulative value on unclosed bars based on the data since the last `anchor` condition. Optional. The default is `false`.
Returns: ( [float, float, float ]) A tuple of three float values. The first element is the current volume. The second is the average of volumes at equivalent time offsets from past anchors over the specified number of periods. The third is the ratio of the current volume to the historical average volume.
rma2(source, length)
An alternate RMA function to the `ta.rma()` built-in, which allows a "series float" `length` argument.
Parameters:
source (float) : (series int/float) Series of values to process.
length (float) : (series int/float) Length for the smoothing parameter calculation.
Returns: (float) The rolling moving average of the `source`.
supertrend2(factor, atrLength, wicks)
An alternate SuperTrend function to `supertrend()`, which allows a "series float" `atrLength` argument.
Parameters:
factor (float) : (series int/float) Multiplier for the ATR value.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
wicks (simple bool) : (simple bool) Condition to determine whether to take candle wicks into account when reversing trend, or to use the close price. Optional. Default is `false`.
Returns: ( [float, int ]) A tuple of the superTrend value and trend direction.
vStop(source, atrLength, atrFactor)
Calculates an ATR-based stop value that trails behind the `source`. Can serve as a possible stop-loss guide and trend identifier.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (simple int) : (simple int) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
vStop2(source, atrLength, atrFactor)
An alternate Volatility Stop function to `vStop()`, which allows a "series float" `atrLength` argument.
Parameters:
source (float) : (series int/float) Series of values that the stop trails behind.
atrLength (float) : (series int/float) Length for the ATR smoothing parameter calculation.
atrFactor (float) : (series int/float) The multiplier of the ATR value. Affects the maximum distance between the stop and the `source` value. A value of 1 means the maximum distance is 100% of the ATR value. Optional. The default is 1.
Returns: ( [float, bool ]) A tuple of the volatility stop value and the trend direction as a "bool".
Removed Functions:
allTimeHigh(src)
Tracks the highest value of `src` from the first historical bar to the current bar.
allTimeLow(src)
Tracks the lowest value of `src` from the first historical bar to the current bar.
trima2(src, length)
An alternate Triangular Moving Average (TRIMA) function to `trima()`, which allows a
"series int" length argument.
TradeChartist PowerTracer ProTradeChartist PowerTracer Pro is an exceptionally well designed and a functional indicator, requiring minimal user input to trace the asset's Bull and Bear Power. The indicator makes it visually engaging with its intelligent positioning of the PowerTracer Bar, tracking not just the current trend, but also the developing trend using visually easy to understand Power plots. PowerTracer Pro can be used with PowerTrader Pro to generate Trade signals with several possible combinations of settings based on PowerTracer Pro Backtester Performance results.
What does ™TradeChartist PowerTracer Pro do?
1. Tracks Bull and Bear Power and plots the information visually on chart using one of the following 2 Power plot options based on Timeframe Multiplier and Smoothing Factor..
𝗣𝗼𝘄𝗲𝗿𝗧𝗿𝗮𝗰𝗲𝗿 - Plot of the Bull and Bear Power Oscillator, pivotal to this script that tracks the true Bull and Bear Power along with Bull/Bear oscillator reading, calculated dynamically using a unique and original formula. Values beyond 50 and -50 are quite rare, but theoretically, they can go beyond 80 and -80. 𝗣𝗼𝘄𝗲𝗿𝗧𝗿𝗮𝗰𝗲𝗿's highs and lows are also tracked and updated real-time using labels placed exactly at the Highs and Lows with their readings.
Bar-wise Power Holder - Absolute Bull and Bear power of each bar. It is plotted by calculating the difference between Bull and Bear Power of each bar. The values can swing between -100 and +100 even though values above 90 and below 90 are rare.
2. Visually displays the Balance of Power between the Bulls and the Bears using Power density background fill.
3. Uses an accompanying 𝗣𝗼𝘄𝗲𝗿𝗧𝗿𝗮𝗰𝗲𝗿 bar that helps spot the true bull and bear power using simple linear blocks, displaying the power level using power intensity colors.
4. Paints price bars and PowerTracer background using Power intensity colors, which helps spot the increase or decrease in Bull and Bear Power. Price bar color changes are based on increasing/decreasing power intensity of the price bar's power holder and may not be the same as the Power plots. This is designed specifically to spot price trends based on chart timeframe power trend.
5. Inverts bar colors, and PowerTracer bar color to help see price trend using the Opponent's Point of View.
What markets can this indicator be used on?
-- Forex
-- Stocks - works best with 4hr or above and prices calculated taking gaps into account.
-- Commodities
-- Cryptocurrencies
and almost any asset on Trading View
What time-frames can this indicator be used on?
This indicator can be used on all timeframes. If the asset has very little volume / volatility or is far low in comparative value against the base currency, power detection can be choppy, but with most assets, this won't be an issue.
Does this indicator repaint?
-- No. Real-time Power plots can change colors and values based on current bar close as values get calculated dynamically. Once the bar closes, plots and power intensity colors don't repaint.
-- This can be verified using Bar Replay to check if the plots and fills stay in the same bar in real time as the Bar Replay
Does the indicator generate trade signals based on Power shifts?
Yes. PowerTracer Pro can be connected to PowerTrader Pro to generate BUY and SELL signals with automatic/user specified targets on the main price chart along with Fixed or Trailing Stop Loss plots based on the Power Plot opted by the user. PowerTrader Pro is highly recommended for traders who would like signals based on power trend on the main price chart as it comes with real time Dashboard and Gains tracker with the option to plot past performance displaying Max gains and Max Drawdowns for each trade. It also includes SL/TP Plots and Alerts system that can be used to automate trades based on settings that result in high ROI on PowerTracer Pro Backtester performance report.
The charts below show how this indicator can be used with PowerTrader Pro to generate trade signals with TP and SL plots.
GBP-USD 1hr chart with SL and TP plots with real-time gains tracker. Timeframe MUltiplier - 2, Smoothing Factor - 8
LINK-BTC 4hr chart with SL and TP plots, real-time gains tracker and past performance results. Timeframe Multiplier - 3, Smoothing Factor - 1
XAU-USD Gold 1hr chart with SL and TP plots, real-time gains on Dashboard with Automatic Targets and past performance labels. Timeframe Multiplier - 2, Smoothing Factor - 1
===================================================================================================================
This is not a free to use indicator. Get in touch with me (PM me directly if you would like trial access to test the indicator)
Premium Scripts - Trial access and Information
Trial access offered on all Premium scripts.
PM me directly to request trial access to the scripts or for more information.
===================================================================================================================
light_logLight Log - A Defensive Programming Library for Pine Script
Overview
The Light Log library transforms Pine Script development by introducing structured logging and defensive programming patterns typically found in enterprise languages like C#. This library addresses a fundamental challenge in Pine Script: the lack of sophisticated error handling and debugging tools that developers expect when building complex trading systems.
At its core, Light Log provides three transformative capabilities that work together to create more reliable and maintainable code. First, it wraps all native Pine Script types in error-aware containers, allowing values to carry validation state alongside their data. Second, it offers a comprehensive logging system with severity levels and conditional rendering. Third, it includes defensive programming utilities that catch errors early and make code self-documenting.
The Philosophy of Errors as Values
Traditional Pine Script error handling relies on runtime errors that halt execution, making it difficult to build resilient systems that can gracefully handle edge cases. Light Log introduces a paradigm shift by treating errors as first-class values that flow through your program alongside regular data.
When you wrap a value using Light Log's type system, you're not just storing data – you're creating a container that can carry both the value and its validation state. For example, when you call myNumber.INT() , you receive an INT object that contains both the integer value and a Log object that can describe any issues with that value. This approach, inspired by functional programming languages, allows errors to propagate through calculations without causing immediate failures.
Consider how this changes error handling in practice. Instead of a calculation failing catastrophically when it encounters invalid input, it can produce a result object that contains both the computed value (which might be na) and a detailed log explaining what went wrong. Subsequent operations can check has_error() to decide whether to proceed or handle the error condition gracefully.
The Typed Wrapper System
Light Log provides typed wrappers for every native Pine Script type: INT, FLOAT, BOOL, STRING, COLOR, LINE, LABEL, BOX, TABLE, CHART_POINT, POLYLINE, and LINEFILL. These wrappers serve multiple purposes beyond simple value storage.
Each wrapper type contains two fields: the value field v holds the actual data, while the error field e contains a Log object that tracks the value's validation state. This dual nature enables powerful programming patterns. You can perform operations on wrapped values and accumulate error information along the way, creating an audit trail of how values were processed.
The wrapper system includes convenient methods for converting between wrapped and unwrapped values. The extension methods like INT() , FLOAT() , etc., make it easy to wrap existing values, while the from_INT() , from_FLOAT() methods extract the underlying values when needed. The has_error() method provides a consistent interface for checking whether any wrapped value has encountered issues during processing.
The Log Object: Your Debugging Companion
The Log object represents the heart of Light Log's debugging capabilities. Unlike simple string concatenation for error messages, the Log object provides a structured approach to building, modifying, and rendering diagnostic information.
Each Log object carries three essential pieces of information: an error type (info, warning, error, or runtime_error), a message string that can be built incrementally, and an active flag that controls conditional rendering. This structure enables sophisticated logging patterns where you can build up detailed diagnostic information throughout your script's execution and decide later whether and how to display it.
The Log object's methods support fluent chaining, allowing you to build complex messages in a readable way. The write() and write_line() methods append text to the log, while new_line() adds formatting. The clear() method resets the log for reuse, and the rendering methods ( render_now() , render_condition() , and the general render() ) control when and how messages appear.
Defensive Programming Made Easy
Light Log's argument validation functions transform how you write defensive code. Instead of cluttering your functions with verbose validation logic, you can use concise, self-documenting calls that make your intentions clear.
The argument_error() function provides strict validation that halts execution when conditions aren't met – perfect for catching programming errors early. For less critical issues, argument_log_warning() and argument_log_error() record problems without stopping execution, while argument_log_info() provides debug visibility into your function's behavior.
These functions follow a consistent pattern: they take a condition to check, the function name, the argument name, and a descriptive message. This consistency makes error messages predictable and helpful, automatically formatting them to show exactly where problems occurred.
Building Modular, Reusable Code
Light Log encourages a modular approach to Pine Script development by providing tools that make functions more self-contained and reliable. When functions validate their inputs and return wrapped values with error information, they become true black boxes that can be safely composed into larger systems.
The void_return() function addresses Pine Script's requirement that all code paths return a value, even in error handling branches. This utility function provides a clean way to satisfy the compiler while making it clear that a particular code path should never execute.
The static log pattern, initialized with init_static_log() , enables module-wide error tracking. You can create a persistent Log object that accumulates information across multiple function calls, building a comprehensive diagnostic report that helps you understand complex behaviors in your indicators and strategies.
Real-World Applications
In practice, Light Log shines when building sophisticated trading systems. Imagine developing a complex indicator that processes multiple data streams, performs statistical calculations, and generates trading signals. With Light Log, each processing stage can validate its inputs, perform calculations, and pass along both results and diagnostic information.
For example, a moving average calculation might check that the period is positive, that sufficient data exists, and that the input series contains valid values. Instead of failing silently or throwing runtime errors, it can return a FLOAT object that contains either the calculated average or a detailed explanation of why the calculation couldn't be performed.
Strategy developers benefit even more from Light Log's capabilities. Complex entry and exit logic often involves multiple conditions that must all be satisfied. With Light Log, each condition check can contribute to a comprehensive log that explains exactly why a trade was or wasn't taken, making strategy debugging and optimization much more straightforward.
Performance Considerations
While Light Log adds a layer of abstraction over raw Pine Script values, its design minimizes performance impact. The wrapper objects are lightweight, containing only two fields. The logging operations only consume resources when actually rendered, and the conditional rendering system ensures that production code can run with logging disabled for maximum performance.
The library follows Pine Script best practices for performance, using appropriate data structures and avoiding unnecessary operations. The var keyword in init_static_log() ensures that persistent logs don't create new objects on every bar, maintaining efficiency even in real-time calculations.
Getting Started
Adopting Light Log in your Pine Script projects is straightforward. Import the library, wrap your critical values, add validation to your functions, and use Log objects to track important events. Start small by adding logging to a single function, then expand as you see the benefits of better error visibility and code organization.
Remember that Light Log is designed to grow with your needs. You can use as much or as little of its functionality as makes sense for your project. Even simple uses, like adding argument validation to key functions, can significantly improve code reliability and debugging ease.
Transform your Pine Script development experience with Light Log – because professional trading systems deserve professional development tools.
Light Log Technical Deep Dive: Advanced Patterns and Architecture
Understanding Errors as Values
The concept of "errors as values" represents a fundamental shift in how we think about error handling in Pine Script. In traditional Pine Script development, errors are events – they happen at a specific moment in time and immediately interrupt program flow. Light Log transforms errors into data – they become information that flows through your program just like any other value.
This transformation has profound implications. When errors are values, they can be stored, passed between functions, accumulated, transformed, and inspected. They become part of your program's data flow rather than exceptions to it. This approach, popularized by languages like Rust with its Result type and Haskell with its Either monad, brings functional programming's elegance to Pine Script.
Consider a practical example. Traditional Pine Script might calculate a momentum indicator like this:
momentum = close - close
If period is invalid or if there isn't enough historical data, this calculation might produce na or cause subtle bugs. With Light Log's approach:
calculate_momentum(src, period)=>
result = src.FLOAT()
if period <= 0
result.e.write("Invalid period: must be positive", true, ErrorType.error)
result.v := na
else if bar_index < period
result.e.write("Insufficient data: need " + str.tostring(period) + " bars", true, ErrorType.warning)
result.v := na
else
result.v := src - src
result.e.write("Momentum calculated successfully", false, ErrorType.info)
result
Now the function returns not just a value but a complete computational result that includes diagnostic information. Calling code can make intelligent decisions based on both the value and its associated metadata.
The Monad Pattern in Pine Script
While Pine Script lacks the type system features to implement true monads, Light Log brings monadic thinking to Pine Script development. The wrapped types (INT, FLOAT, etc.) act as computational contexts that carry both values and metadata through a series of transformations.
The key insight of monadic programming is that you can chain operations while automatically propagating context. In Light Log, this context is the error state. When you have a FLOAT that contains an error, operations on that FLOAT can check the error state and decide whether to proceed or propagate the error.
This pattern enables what functional programmers call "railway-oriented programming" – your code follows a success track when all is well but can switch to an error track when problems occur. Both tracks lead to the same destination (a result with error information), but they take different paths based on the validity of intermediate values.
Composable Error Handling
Light Log's design encourages composition – building complex functionality from simpler, well-tested components. Each component can validate its inputs, perform its calculation, and return a result with appropriate error information. Higher-level functions can then combine these results intelligently.
Consider building a complex trading signal from multiple indicators:
generate_signal(src, fast_period, slow_period, signal_period) =>
log = init_static_log(ErrorType.info)
// Calculate components with error tracking
fast_ma = calculate_ma(src, fast_period)
slow_ma = calculate_ma(src, slow_period)
// Check for errors in components
if fast_ma.has_error()
log.write_line("Fast MA error: " + fast_ma.e.message, true)
if slow_ma.has_error()
log.write_line("Slow MA error: " + slow_ma.e.message, true)
// Proceed with calculation if no errors
signal = 0.0.FLOAT()
if not (fast_ma.has_error() or slow_ma.has_error())
macd_line = fast_ma.v - slow_ma.v
signal_line = calculate_ma(macd_line, signal_period)
if signal_line.has_error()
log.write_line("Signal line error: " + signal_line.e.message, true)
signal.e := log
else
signal.v := macd_line - signal_line.v
log.write("Signal generated successfully")
else
signal.e := log
signal.v := na
signal
This composable approach makes complex calculations more reliable and easier to debug. Each component is responsible for its own validation and error reporting, and the composite function orchestrates these components while maintaining comprehensive error tracking.
The Static Log Pattern
The init_static_log() function introduces a powerful pattern for maintaining state across function calls. In Pine Script, the var keyword creates variables that persist across bars but are initialized only once. Light Log leverages this to create logging objects that can accumulate information throughout a script's execution.
This pattern is particularly valuable for debugging complex strategies where you need to understand behavior across multiple bars. You can create module-level logs that track important events:
// Module-level diagnostic log
diagnostics = init_static_log(ErrorType.info)
// Track strategy decisions across bars
check_entry_conditions() =>
diagnostics.clear() // Start fresh each bar
diagnostics.write_line("Bar " + str.tostring(bar_index) + " analysis:")
if close > sma(close, 20)
diagnostics.write_line("Price above SMA20", false)
else
diagnostics.write_line("Price below SMA20 - no entry", true, ErrorType.warning)
if volume > sma(volume, 20) * 1.5
diagnostics.write_line("Volume surge detected", false)
else
diagnostics.write_line("Normal volume", false)
// Render diagnostics based on verbosity setting
if debug_mode
diagnostics.render_now()
Advanced Validation Patterns
Light Log's argument validation functions enable sophisticated precondition checking that goes beyond simple null checks. You can implement complex validation logic while keeping your code readable:
validate_price_data(open_val, high_val, low_val, close_val) =>
argument_error(na(open_val) or na(high_val) or na(low_val) or na(close_val),
"validate_price_data", "OHLC values", "contain na values")
argument_error(high_val < low_val,
"validate_price_data", "high/low", "high is less than low")
argument_error(close_val > high_val or close_val < low_val,
"validate_price_data", "close", "is outside high/low range")
argument_log_warning(high_val == low_val,
"validate_price_data", "high/low", "are equal (no range)")
This validation function documents its requirements clearly and fails fast with helpful error messages when assumptions are violated. The mix of errors (which halt execution) and warnings (which allow continuation) provides fine-grained control over how strict your validation should be.
Performance Optimization Strategies
While Light Log adds abstraction, careful design minimizes overhead. Understanding Pine Script's execution model helps you use Light Log efficiently.
Pine Script executes once per bar, so operations that seem expensive in traditional programming might have negligible impact. However, when building real-time systems, every optimization matters. Light Log provides several patterns for efficient use:
Lazy Evaluation: Log messages are only built when they'll be rendered. Use conditional logging to avoid string concatenation in production:
if debug_mode
log.write_line("Calculated value: " + str.tostring(complex_calculation))
Selective Wrapping: Not every value needs error tracking. Wrap values at API boundaries and critical calculation points, but use raw values for simple operations:
// Wrap at boundaries
input_price = close.FLOAT()
validated_period = validate_period(input_period).INT()
// Use raw values internally
sum = 0.0
for i = 0 to validated_period.v - 1
sum += close
Error Propagation: When errors occur early, avoid expensive calculations:
process_data(input) =>
validated = validate_input(input)
if validated.has_error()
validated // Return early with error
else
// Expensive processing only if valid
perform_complex_calculation(validated)
Integration Patterns
Light Log integrates smoothly with existing Pine Script code. You can adopt it incrementally, starting with critical functions and expanding coverage as needed.
Boundary Validation: Add Light Log at the boundaries of your system – where user input enters and where final outputs are produced. This catches most errors while minimizing changes to existing code.
Progressive Enhancement: Start by adding argument validation to existing functions. Then wrap return values. Finally, add comprehensive logging. Each step improves reliability without requiring a complete rewrite.
Testing and Debugging: Use Light Log's conditional rendering to create debug modes for your scripts. Production users see clean output while developers get detailed diagnostics:
// User input for debug mode
debug = input.bool(false, "Enable debug logging")
// Conditional diagnostic output
if debug
diagnostics.render_now()
else
diagnostics.render_condition() // Only shows errors/warnings
Future-Proofing Your Code
Light Log's patterns prepare your code for Pine Script's evolution. As Pine Script adds more sophisticated features, code that uses structured error handling and defensive programming will adapt more easily than code that relies on implicit assumptions.
The type wrapper system, in particular, positions your code to take advantage of potential future features or more sophisticated type inference. By thinking in terms of wrapped values and error propagation today, you're building code that will remain maintainable and extensible tomorrow.
Light Log doesn't just make your Pine Script better today – it prepares it for the trading systems you'll need to build tomorrow.
Library "light_log"
A lightweight logging and defensive programming library for Pine Script.
Designed for modular and extensible scripts, this utility provides structured runtime validation,
conditional logging, and reusable `Log` objects for centralized error propagation.
It also introduces a typed wrapping system for all native Pine values (e.g., `INT`, `FLOAT`, `LABEL`),
allowing values to carry errors alongside data. This enables functional-style flows with built-in
validation tracking, error detection (`has_error()`), and fluent chaining.
Inspired by structured logging patterns found in systems like C#, it reduces boilerplate,
enforces argument safety, and encourages clean, maintainable code architecture.
method INT(self, error_type)
Wraps an `int` value into an `INT` struct with an optional log severity.
Namespace types: series int, simple int, input int, const int
Parameters:
self (int) : The raw `int` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: An `INT` object containing the value and a default Log instance.
method FLOAT(self, error_type)
Wraps a `float` value into a `FLOAT` struct with an optional log severity.
Namespace types: series float, simple float, input float, const float
Parameters:
self (float) : The raw `float` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `FLOAT` object containing the value and a default Log instance.
method BOOL(self, error_type)
Wraps a `bool` value into a `BOOL` struct with an optional log severity.
Namespace types: series bool, simple bool, input bool, const bool
Parameters:
self (bool) : The raw `bool` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `BOOL` object containing the value and a default Log instance.
method STRING(self, error_type)
Wraps a `string` value into a `STRING` struct with an optional log severity.
Namespace types: series string, simple string, input string, const string
Parameters:
self (string) : The raw `string` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `STRING` object containing the value and a default Log instance.
method COLOR(self, error_type)
Wraps a `color` value into a `COLOR` struct with an optional log severity.
Namespace types: series color, simple color, input color, const color
Parameters:
self (color) : The raw `color` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `COLOR` object containing the value and a default Log instance.
method LINE(self, error_type)
Wraps a `line` object into a `LINE` struct with an optional log severity.
Namespace types: series line
Parameters:
self (line) : The raw `line` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LINE` object containing the value and a default Log instance.
method LABEL(self, error_type)
Wraps a `label` object into a `LABEL` struct with an optional log severity.
Namespace types: series label
Parameters:
self (label) : The raw `label` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LABEL` object containing the value and a default Log instance.
method BOX(self, error_type)
Wraps a `box` object into a `BOX` struct with an optional log severity.
Namespace types: series box
Parameters:
self (box) : The raw `box` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `BOX` object containing the value and a default Log instance.
method TABLE(self, error_type)
Wraps a `table` object into a `TABLE` struct with an optional log severity.
Namespace types: series table
Parameters:
self (table) : The raw `table` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `TABLE` object containing the value and a default Log instance.
method CHART_POINT(self, error_type)
Wraps a `chart.point` value into a `CHART_POINT` struct with an optional log severity.
Namespace types: chart.point
Parameters:
self (chart.point) : The raw `chart.point` value to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `CHART_POINT` object containing the value and a default Log instance.
method POLYLINE(self, error_type)
Wraps a `polyline` object into a `POLYLINE` struct with an optional log severity.
Namespace types: series polyline, series polyline, series polyline, series polyline
Parameters:
self (polyline) : The raw `polyline` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `POLYLINE` object containing the value and a default Log instance.
method LINEFILL(self, error_type)
Wraps a `linefill` object into a `LINEFILL` struct with an optional log severity.
Namespace types: series linefill
Parameters:
self (linefill) : The raw `linefill` object to wrap.
error_type (series ErrorType) : Optional severity level to associate with the log. Default is `ErrorType.error`.
Returns: A `LINEFILL` object containing the value and a default Log instance.
method from_INT(self)
Extracts the integer value from an INT wrapper.
Namespace types: INT
Parameters:
self (INT) : The wrapped INT instance.
Returns: The underlying `int` value.
method from_FLOAT(self)
Extracts the float value from a FLOAT wrapper.
Namespace types: FLOAT
Parameters:
self (FLOAT) : The wrapped FLOAT instance.
Returns: The underlying `float` value.
method from_BOOL(self)
Extracts the boolean value from a BOOL wrapper.
Namespace types: BOOL
Parameters:
self (BOOL) : The wrapped BOOL instance.
Returns: The underlying `bool` value.
method from_STRING(self)
Extracts the string value from a STRING wrapper.
Namespace types: STRING
Parameters:
self (STRING) : The wrapped STRING instance.
Returns: The underlying `string` value.
method from_COLOR(self)
Extracts the color value from a COLOR wrapper.
Namespace types: COLOR
Parameters:
self (COLOR) : The wrapped COLOR instance.
Returns: The underlying `color` value.
method from_LINE(self)
Extracts the line object from a LINE wrapper.
Namespace types: LINE
Parameters:
self (LINE) : The wrapped LINE instance.
Returns: The underlying `line` object.
method from_LABEL(self)
Extracts the label object from a LABEL wrapper.
Namespace types: LABEL
Parameters:
self (LABEL) : The wrapped LABEL instance.
Returns: The underlying `label` object.
method from_BOX(self)
Extracts the box object from a BOX wrapper.
Namespace types: BOX
Parameters:
self (BOX) : The wrapped BOX instance.
Returns: The underlying `box` object.
method from_TABLE(self)
Extracts the table object from a TABLE wrapper.
Namespace types: TABLE
Parameters:
self (TABLE) : The wrapped TABLE instance.
Returns: The underlying `table` object.
method from_CHART_POINT(self)
Extracts the chart.point from a CHART_POINT wrapper.
Namespace types: CHART_POINT
Parameters:
self (CHART_POINT) : The wrapped CHART_POINT instance.
Returns: The underlying `chart.point` value.
method from_POLYLINE(self)
Extracts the polyline object from a POLYLINE wrapper.
Namespace types: POLYLINE
Parameters:
self (POLYLINE) : The wrapped POLYLINE instance.
Returns: The underlying `polyline` object.
method from_LINEFILL(self)
Extracts the linefill object from a LINEFILL wrapper.
Namespace types: LINEFILL
Parameters:
self (LINEFILL) : The wrapped LINEFILL instance.
Returns: The underlying `linefill` object.
method has_error(self)
Returns true if the INT wrapper has an active log entry.
Namespace types: INT
Parameters:
self (INT) : The INT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the FLOAT wrapper has an active log entry.
Namespace types: FLOAT
Parameters:
self (FLOAT) : The FLOAT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the BOOL wrapper has an active log entry.
Namespace types: BOOL
Parameters:
self (BOOL) : The BOOL instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the STRING wrapper has an active log entry.
Namespace types: STRING
Parameters:
self (STRING) : The STRING instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the COLOR wrapper has an active log entry.
Namespace types: COLOR
Parameters:
self (COLOR) : The COLOR instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LINE wrapper has an active log entry.
Namespace types: LINE
Parameters:
self (LINE) : The LINE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LABEL wrapper has an active log entry.
Namespace types: LABEL
Parameters:
self (LABEL) : The LABEL instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the BOX wrapper has an active log entry.
Namespace types: BOX
Parameters:
self (BOX) : The BOX instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the TABLE wrapper has an active log entry.
Namespace types: TABLE
Parameters:
self (TABLE) : The TABLE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the CHART_POINT wrapper has an active log entry.
Namespace types: CHART_POINT
Parameters:
self (CHART_POINT) : The CHART_POINT instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the POLYLINE wrapper has an active log entry.
Namespace types: POLYLINE
Parameters:
self (POLYLINE) : The POLYLINE instance to check.
Returns: True if an error or message is active in the log.
method has_error(self)
Returns true if the LINEFILL wrapper has an active log entry.
Namespace types: LINEFILL
Parameters:
self (LINEFILL) : The LINEFILL instance to check.
Returns: True if an error or message is active in the log.
void_return()
Utility function used when a return is syntactically required but functionally unnecessary.
Returns: Nothing. Function never executes its body.
argument_error(condition, function, argument, message)
Throws a runtime error when a condition is met. Used for strict argument validation.
Parameters:
condition (bool) : Boolean expression that triggers the runtime error.
function (string) : Name of the calling function (for formatting).
argument (string) : Name of the problematic argument.
message (string) : Description of the error cause.
Returns: Never returns. Halts execution if the condition is true.
argument_log_info(condition, function, argument, message)
Logs an informational message when a condition is met. Used for optional debug visibility.
Parameters:
condition (bool) : Boolean expression that triggers the log.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Informational message to log.
Returns: Nothing. Logs if the condition is true.
argument_log_warning(condition, function, argument, message)
Logs a warning when a condition is met. Non-fatal but highlights potential issues.
Parameters:
condition (bool) : Boolean expression that triggers the warning.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Warning message to log.
Returns: Nothing. Logs if the condition is true.
argument_log_error(condition, function, argument, message)
Logs an error message when a condition is met. Does not halt execution.
Parameters:
condition (bool) : Boolean expression that triggers the error log.
function (string) : Name of the calling function.
argument (string) : Argument name being referenced.
message (string) : Error message to log.
Returns: Nothing. Logs if the condition is true.
init_static_log(error_type, message, active)
Initializes a persistent (var) Log object. Ideal for global logging in scripts or modules.
Parameters:
error_type (series ErrorType) : Initial severity level (required).
message (string) : Optional starting message string. Default value of ("").
active (bool) : Whether the log should be flagged active on initialization. Default value of (false).
Returns: A static Log object with the given parameters.
method new_line(self)
Appends a newline character to the Log message. Useful for separating entries during chained writes.
Namespace types: Log
Parameters:
self (Log) : The Log instance to modify.
Returns: The updated Log object with a newline appended.
method write(self, message, flag_active, error_type)
Appends a message to a Log object without a newline. Updates severity and active state if specified.
Namespace types: Log
Parameters:
self (Log) : The Log instance being modified.
message (string) : The text to append to the log.
flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
Returns: The updated Log object.
method write_line(self, message, flag_active, error_type)
Appends a message to a Log object, prefixed with a newline for clarity.
Namespace types: Log
Parameters:
self (Log) : The Log instance being modified.
message (string) : The text to append to the log.
flag_active (bool) : Whether to activate the log for conditional rendering. Default value of (false).
error_type (series ErrorType) : Optional override for the severity level. Default value of (na).
Returns: The updated Log object.
method clear(self, flag_active, error_type)
Clears a Log object’s message and optionally reactivates it. Can also update the error type.
Namespace types: Log
Parameters:
self (Log) : The Log instance being cleared.
flag_active (bool) : Whether to activate the log after clearing. Default value of (false).
error_type (series ErrorType) : Optional new error type to assign. If not provided, the previous type is retained. Default value of (na).
Returns: The cleared Log object.
method render_condition(self, flag_active, error_type)
Conditionally renders the log if it is active. Allows overriding error type and controlling active state afterward.
Namespace types: Log
Parameters:
self (Log) : The Log instance to evaluate and render.
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override. Useful for contextual formatting just before rendering. Default value of (na).
Returns: The updated Log object.
method render_now(self, flag_active, error_type)
Immediately renders the log regardless of `active` state. Allows overriding error type and active flag.
Namespace types: Log
Parameters:
self (Log) : The Log instance to render.
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override. Allows dynamic severity adjustment at render time. Default value of (na).
Returns: The updated Log object.
render(self, condition, flag_active, error_type)
Renders the log conditionally or unconditionally. Allows full control over render behavior.
Parameters:
self (Log) : The Log instance to render.
condition (bool) : If true, renders only if the log is active. If false, always renders. Default value of (false).
flag_active (bool) : Whether to activate the log after rendering. Default value of (false).
error_type (series ErrorType) : Optional error type override passed to the render methods. Default value of (na).
Returns: The updated Log object.
Log
A structured object used to store and render logging messages.
Fields:
error_type (series ErrorType) : The severity level of the message (from the ErrorType enum).
message (series string) : The text of the log message.
active (series bool) : Whether the log should trigger rendering when conditionally evaluated.
INT
A wrapped integer type with attached logging for validation or tracing.
Fields:
v (series int) : The underlying `int` value.
e (Log) : Optional log object describing validation status or error context.
FLOAT
A wrapped float type with attached logging for validation or tracing.
Fields:
v (series float) : The underlying `float` value.
e (Log) : Optional log object describing validation status or error context.
BOOL
A wrapped boolean type with attached logging for validation or tracing.
Fields:
v (series bool) : The underlying `bool` value.
e (Log) : Optional log object describing validation status or error context.
STRING
A wrapped string type with attached logging for validation or tracing.
Fields:
v (series string) : The underlying `string` value.
e (Log) : Optional log object describing validation status or error context.
COLOR
A wrapped color type with attached logging for validation or tracing.
Fields:
v (series color) : The underlying `color` value.
e (Log) : Optional log object describing validation status or error context.
LINE
A wrapped line object with attached logging for validation or tracing.
Fields:
v (series line) : The underlying `line` value.
e (Log) : Optional log object describing validation status or error context.
LABEL
A wrapped label object with attached logging for validation or tracing.
Fields:
v (series label) : The underlying `label` value.
e (Log) : Optional log object describing validation status or error context.
BOX
A wrapped box object with attached logging for validation or tracing.
Fields:
v (series box) : The underlying `box` value.
e (Log) : Optional log object describing validation status or error context.
TABLE
A wrapped table object with attached logging for validation or tracing.
Fields:
v (series table) : The underlying `table` value.
e (Log) : Optional log object describing validation status or error context.
CHART_POINT
A wrapped chart point with attached logging for validation or tracing.
Fields:
v (chart.point) : The underlying `chart.point` value.
e (Log) : Optional log object describing validation status or error context.
POLYLINE
A wrapped polyline object with attached logging for validation or tracing.
Fields:
v (series polyline) : The underlying `polyline` value.
e (Log) : Optional log object describing validation status or error context.
LINEFILL
A wrapped linefill object with attached logging for validation or tracing.
Fields:
v (series linefill) : The underlying `linefill` value.
e (Log) : Optional log object describing validation status or error context.
AlgoCados x ICT ToolkitAlgoCados x ICT Toolkit is a TradingView tool designed to integrate ICT (Inner Circle Trader) Smart Money Concepts (SMC) into a structured trading framework.
It provides traders with institutional liquidity insights, precise price level tracking, and session-based analysis, making it an essential tool for intraday, swing, and position trading.
Optimized for Forex, Futures, and Crypto, this toolkit offers multi-timeframe liquidity tracking, killzone mapping, RTH analysis, standard deviation projections, and dynamic price level updates, ensuring traders stay aligned with institutional market behavior.
# Key Features
Multi-Timeframe Institutional Price Levels
The indicator provides a structured approach to analyzing liquidity and market structure across different time horizons, helping traders understand institutional order flow.
- Previous Day High/Low (PDH/PDL) – Tracks the Previous Day’s High/Low, crucial for intraday liquidity analysis.
- Previous Week High/Low (PWH/PWL) – Monitors the Previous Week’s High/Low, aiding in higher timeframe liquidity zone tracking.
- Previous Month High/Low (PMH/PML) – Highlights the Previous Month’s High/Low, critical for swing trading and long-term bias confirmation.
- True Day Open (TDO) – Marks the NY Midnight Opening Price, providing a reference point for intraday bias and liquidity movements.
- Automatic Level Cleanup – When enabled. pxHigh/pxLow levels gets automatically deleted when raided, keeping the chart clean and focused on valid liquidity zones.
- Monthly, Weekly, Daily Open Levels – Identifies HTF price action context, allowing traders to track institutional order flow and potential liquidity draws.
# Regular Trading Hours (RTH) High, Low & Mid-Equilibrium (EQ)
For futures traders, the toolkit accurately identifies RTH liquidity zones to align with institutional trading behavior.
- RTH High/Low (RTH H/L) – Defines the RTH Gap high and low dynamically, marking key liquidity levels.
- RTH Equilibrium (EQ) – Calculates the midpoint of the RTH range, acting as a mean reversion level where price often reacts.
# Killzones & Liquidity Mapping
The indicator provides a time-based liquidity structure that helps traders anticipate market movements during high-impact trading windows.
ICT Killzones (Visible on 30-minute timeframe or lower)
- Asia Killzone (Asia) – Tracks overnight liquidity accumulation.
- London Open Killzone (LOKZ) – Marks early European liquidity grabs.
- New York Killzone (NYKZ) – Captures US session volatility.
- New York PM Session (PMKZ) – Available only for futures markets, tracking late-day liquidity shifts.
Forex-Specific Killzones (Visible on 30-minute timeframe or lower)
- London Close Killzone (LCKZ) – Available only for Forex, marks the European end of Day liquidity Points of Interests (POI).
- Central Bank Dealers Range (CBDR) – Available only for Forex, providing a liquidity framework used by central banks.
- Flout (CBDR + Asian Range) – Available only for Forex, extending CBDR with Asian session liquidity behavior.
- Killzone History Option – When enabled, Killzones remain visible beyond the current day; otherwise, they reset daily.
- Customizable Killzone Boxes – Modify opacity, colors, and border styles for seamless integration into different trading styles.
CME_MINI:NQH2025 FOREXCOM:EURUSD
# Standard Deviation (STDV) Liquidity Projections
A statistical approach to forecasting price movements based on Standard Deviations of HOTD (High of the Day) and LOTD (Low of the Day).
- Asia, CBDR, and Flout STDV Calculations (Visible on 30-minute timeframe or lower) – Predicts liquidity grabs based on price expansion behavior.
- Customizable Display Modes – Choose between Compact (e.g., "+2.5") or Verbose (e.g., "Asia +2.5") labels.
- Real-Time STDV Updates – Projections dynamically adjust as new price data is formed, allowing traders to react to developing market conditions.
CME_MINI:NQH2025
# Daily Session Dividers
- Visualizes Trading Days (Visible on 1-hour timeframe or lower) – Helps segment the trading session for better structure analysis.
- Daily Divider History Option – When enabled, dividers remain visible beyond the current trading week; otherwise, they reset weekly.
# Customization & User Experience
- Flexible Label Options – Adjust label size, font type, and color for improved readability.
- Intraday-Optimized Data – Killzones (30m or lower), STDV (30m or lower), and Daily Dividers (1H or lower) ensure efficient use of chart space.
- Configurable Line Styles – Customize solid, dotted, or dashed styles for various levels, making charts aesthetically clean and data-rich.
# Usage & Configurations
The AlgoCados x ICT Toolkit is designed to seamlessly fit different trading methodologies.
Scalping & Intraday Trading
- Track PDH/PDL levels for liquidity sweeps and market reversals.
- Utilize Killzones & Session Open levels to identify high-probability entry zones.
- Analyze RTH High/Low & Mid-EQ for potential liquidity targets and reversals.
- Enable STDV projections for potential price expansion and reversals.
Swing & Position Trading
- Use PWH/PWL and PMH/PML levels to determine HTF liquidity shifts.
- Monitor RTH Gap, TDO, and session liquidity markers for trade confirmation.
- Combine HTF bias with LTF liquidity structures for optimized entries and exits.
# Inputs & Configuration Options
Customizable Parameters
- Offset Adjustment – Allows users to shift displayed data horizontally for better visibility.
- Killzone Box Styling – Customize colors, opacity, and border styles for session boxes.
- Session Dividers – Modify line styles and colors for better time segmentation.
- Killzone & Daily Divider History Toggle – Enables users to view past killzones and dividers instead of resetting them daily/weekly.
- Label Formatting – Toggle between Compact and Verbose display modes for streamlined analysis.
# Advanced Features
Real-Time Data Processing & Dynamic Object Management
- Auto Cleanup of pxLevels – Prevents clutter by removing invalidated levels upon liquidity raids.
- Session History Control – Users can toggle historical data for daily dividers and killzones to maintain a clean chart layout.
- Daily & Weekly Resets – Ensures accurate session tracking by resetting daily dividers at the start of each new trading week.
CME_MINI:NQH2025
# Example Use Cases
- Day Traders & Scalpers – Utilize Killzones, PDH/PDL, DO and TDO levels for precise liquidity-based trading opportunities.
- Swing Traders – Leverage HTF Open Levels, PWH/PWL liquidity mapping, and TDO for trend-based trade execution.
- Futures Traders – Optimize trading with RTH High/Low, Mid-EQ, and PMKZ for session liquidity tracking.
- Forex Traders – Use CBDR, Flout, and session liquidity mapping to align with institutional order flow.
CME_MINI:ESH2025
"By integrating institutional concepts, liquidity mapping, and smart money methodologies, the AlgoCados x ICT Toolkit empowers traders with a data-driven approach to market inefficiencies and liquidity pools."
# Disclaimer
This tool is designed to assist in trading decisions but should be used in conjunction with other analysis methods and proper risk management. Trading involves significant risk, and traders should ensure they understand market conditions before executing trades.
Fibonacci Optimal Entry Zone [OTE] (Zeiierman)█ Overview
Fibonacci Optimal Entry Zone (Zeiierman) is a high-precision market structure tool designed to help traders identify ideal entry zones during trending markets. Built on the principles of Smart Money Concepts (SMC) and Fibonacci retracements, this indicator highlights key areas where price is most likely to react — specifically within the "Golden Zone" (between the 50% and 61.8% retracement).
It tracks structural pivot shifts (CHoCH) and dynamically adjusts Fibonacci levels based on real-time swing tracking. Whether you're trading breakouts, pullbacks, or optimal entries, this tool brings unparalleled clarity to structure-based strategies.
Ideal for traders who rely on confluence, this indicator visually synchronizes swing highs/lows, market structure shifts, Fibonacci retracement levels, and trend alignment — all without clutter or lag.
⚪ The Structural Assumption
Price moves in waves, but key retracements often lead to continuation or reversal — especially when aligned with structure breaks and trend shifts.
The Optimal Entry Zone captures this behavior by anchoring Fibonacci levels between recent swing extremes. The most powerful area — the Golden Zone — marks where institutional re-entry is likely, providing traders with a sniper-like roadmap to structure-based entries.
█ How It Works
⚪ Structure Tracking Engine
At its core, the indicator detects pivots and classifies trend direction:
Structure Period – Determines the depth of pivots used to detect swing highs/lows.
CHoCH – Break of structure logic identifies where the trend shifts or continues, marked visually on the chart.
Bullish & Bearish Modes – Independently toggle uptrend and downtrend detection and styling.
⚪ Fibonacci Engine
Upon each confirmed structural shift, Fibonacci retracement levels are projected between swing extremes:
Custom Levels – Choose which retracements (0.50, 0.618, etc.) are shown.
Real-Time Adjustments – When "Swing Tracker" is enabled, levels and labels update dynamically as price forms new swings.
Example:
If you disable the Swing Tracker, the Golden Level is calculated using the most recent confirmed swing high and low.
If you enable the Swing Tracker, the Golden Level is calculated from the latest swing high or low, making it more adaptive as the trend evolves in real time.
█ How to Use
⚪ Structure-Based Entry
Wait for CHoCH events and use the resulting Fibonacci projection to identify entry points. Enter trades as price taps into the Golden Zone, especially when confluence forms with swing structure or order blocks.
⚪ Real-Time Reaction Tracking
Enable Swing Tracker to keep the tool live — constantly updating zones as price shifts. This is especially useful for scalpers or intraday traders who rely on fresh swing zones.
█ Settings
Structure Period – Number of bars used to define swing pivots. Larger values = stronger structure.
Swing Tracker – Auto-updates fib levels as new highs/lows form.
Show Previous Levels – Keep older fib zones on chart or reset with each structure shift.
-----------------
Disclaimer
The content provided in my scripts, indicators, ideas, algorithms, and systems is for educational and informational purposes only. It does not constitute financial advice, investment recommendations, or a solicitation to buy or sell any financial instruments. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.