Super Optimized SMA 20/200 Strategy - Long & Short_grok### Description of the SMA 20/200 Trading Strategy with Proposed Optimizations
The "Super Optimized SMA 20/200 Strategy - Long & Short" is a technical trading strategy designed for TradingView, leveraging two Simple Moving Averages (SMA) — a 20-period SMA for short-term trend detection and a 200-period SMA for long-term support/resistance — to identify entry and exit points for both long and short positions. Originally inspired by Emmanuel Malyarovich's minimalist approach, the strategy has been enhanced with optimizations to improve profitability, reduce risk, and adapt to volatile markets like cryptocurrencies (e.g., XRPUSD). Below is a detailed description of the base strategy and the proposed optimizations.
#### **Base Strategy Overview**
- **Indicators Used**:
- **20 SMA**: Tracks short-term trends and serves as a dynamic support/resistance level for bounce entries.
- **200 SMA**: Acts as a long-term support (for long entries) or resistance (for short entries).
- **Entry Logic**:
- **Long Entry**: Triggered when the price bounces off the 20 SMA in an uptrend (20 SMA sloping upward over the last 3 bars), with the low touching or slightly below the 20 SMA and the close above it. The price must also be above the 200 SMA for confirmation.
- **Short Entry**: Triggered when the price rebounds off the 20 SMA in a downtrend (20 SMA sloping downward), with the high touching or slightly above the 20 SMA and the close below it. The price must be below the 200 SMA.
- **Exit Logic**:
- Default settings include a 2% take profit (TP) and 1% stop loss (SL) for both long and short positions.
- A trailing stop with a 0.1% offset can be activated to lock in profits during strong trends.
- **Visuals and Alerts**: The strategy plots 20 SMA (blue) and 200 SMA (red) on the chart, with green triangles for long entries and red triangles for short entries. Alerts notify users of entry signals with price details.
- **Initial Settings**: Starts with $10,000 capital, using 10% of equity per trade.
#### **Proposed Optimizations**
To address the observed 2% profitability (improved to 112% with trailing stop) and align with your feedback (e.g., 1H outperforming 4H, tolerance at 0.1% working well), the following enhancements have been integrated into the strategy:
1. **Flexible Take Profit and Trailing Stop**:
- Added a `useTakeProfit` boolean (default true) to toggle TP. If set to false, only the trailing stop (0.1% offset) is used, allowing unlimited profit capture in strong trends. This addresses your request to disable TP, potentially boosting profitability in bull/bear runs while increasing drawdown risk.
- **Recommendation**: Test with TP off on 1H for XRPUSD to confirm 112% holds; adjust offset to 0.2% if drawdown exceeds 20%.
2. **Dynamic Stop Loss with ATR**:
- Replaced fixed 1% SL with a dynamic SL based on ATR(14) * 1.5, calculated as `close * (1 - (ATR * multiplier / close))` for long and the inverse for short. Inputs `atrLength` (14) and `atrMultiplier` (1.5) are adjustable.
- **Benefit**: Adapts to market volatility, reducing premature exits in choppy conditions. Test with multiplier 1-2 to balance risk/reward.
- **Note**: A `useAtrStop` toggle (default true) allows reverting to fixed SL if needed.
3. **Tolerance for Pullback Adjustment**:
- Set to 0.1% (your successful tweak), allowing precise bounce detection. The strategy checks if the low is within ±0.1% of 20 SMA, with the close crossing above for long or below for short.
- **Optimization**: If trades are too few, increase to 0.3-0.5% to capture more opportunities, as seen in your original script’s 0.5% tolerance.
4. **RSI Filter**:
- Integrated RSI(14) with configurable `rsiOverbought` (default 70) and `rsiOversold` (default 30). Long entries require RSI > oversoldLevel, and short entries require RSI < overboughtLevel.
- **Benefit**: Filters out overbought/oversold conditions, improving signal quality. Test with neutral levels (50) for broader entries, potentially adding 10-20% to profitability.
5. **Market Sideways Filter**:
- Added a `sma20_flat` condition, checking if the 20 SMA variation over the last 5 bars (`flatCheckBars`) is below a `flatTolerance` (0.001). If true, entries are blocked.
- **Benefit**: Reduces false signals in range-bound markets, lowering drawdown. Adjust `flatCheckBars` to 3-7 based on volatility.
6. **Time/Day Filter**:
- Restricts trading to active hours (default 8:00-20:00 UTC, adjustable with `startHour` and `endHour`) and excludes weekends (Saturday/Sunday).
- **Benefit**: Focuses on high-volume periods in crypto, improving winning rate. Adjust hours to 9:00-17:00 UTC if testing on BTCUSD/ETHUSD.
7. **Volume Filter**:
- Retained from your script, with `minVolume` (default 0, disabled) to filter low-liquidity trades.
- **Optimization**: Set to a symbol-specific minimum (e.g., 10,000 for XRPUSD) to avoid slippage.
#### **Implementation Details**
- The strategy uses `strategy.entry` and `strategy.exit` with conditional logic for TP, SL, and trailing stops. Visuals (triangles) and alerts remain for manual oversight.
- Inputs are fully customizable, allowing backtesting to fine-tune parameters.
#### **Testing Recommendations**
- **Timeframe**: Stick to 1H for XRPUSD, as 4H underperformed. Test 2H or Daily on BTCUSD/ETHUSD for stability.
- **Symbols**: Beyond XRPUSD, try BTCUSD (stable) or ETHUSD (volatile but liquid) to diversify gains.
- **Backtesting**: Run on the last 2 years (Oct 2023-Oct 2025), with 70% for optimization and 30% for out-of-sample testing. Include 0.1% commissions and 0.05% slippage.
- **Metrics to Watch**: Aim for profit >6%, drawdown <30%, and winning rate >50%. If 112% persists, validate with live demo trading.
#### **Next Steps**
This optimized strategy balances your successful tweaks (0.1% tolerance, trailing stop) with robust filters (RSI, sideways, time). Test on TradingView, adjust inputs based on results, and report back with drawdown or trade count for further tuning!
지표 및 전략
RSI Breakout Zones█ OVERVIEW
“RSI Breakout Zones” is a technical analysis tool that identifies significant zones on the chart based on the Relative Strength Index (RSI). The indicator maps overbought (OB) and oversold (OS) zones using boxes, then extends them until the next zone of the same type is detected, highlighting breakout points to aid in trade entry decisions. These zones often serve as areas of consolidation, support, or resistance.
█ CONCEPTS
The indicator identifies overbought (above 70) and oversold (below 30) zones, drawing boxes that extend until the next zone of the same type (OB for OB, OS for OS) is detected. Breakout signals are generated when the price crosses the zone boundaries, indicating potential shifts in market momentum.
Why are RSI zones important? These zones represent areas of extreme market sentiment, often leading to corrections or reversals. Overbought zones suggest potential selling pressure, while oversold zones indicate buying opportunities. After a breakout, a zone may switch roles, e.g., from support to resistance or vice versa, making it a key element in price action analysis. Larger zones, formed during high volatility, may attract price for retests due to stronger imbalances in buyer/seller dynamics. Consolidation often occurs within these zones as the market seeks equilibrium before further moves. However, in strong trends, zones may be decisively broken without immediate pullbacks, and their significance depends on their position relative to key support and resistance levels.
█ FEATURES
- RSI Zone Detection: Calculates RSI with a customizable length (default 14) and identifies overbought/oversold zones based on user-defined levels (default 70/30), drawing boxes that dynamically adjust to price action within the zone.
- Customizable Boxes: Zones extend until the next zone of the same type is detected. The indicator draws zones with adjustable colors for overbought (red) and oversold (green) areas, with options for box and zone transparency.
- Breakout Signals: Generates upward (green triangle) and downward (red triangle) breakout signals when the price crosses the top or bottom of a zone. Signals appear below or above the bar, indicating potential trade entry points.
- Midline: Automatically draws a dashed line at the midpoint of each zone, helping traders assess price behavior within the zone and potential halfway retests.
- Box Management: Option to remove outdated boxes.
- Alerts: Built-in support for alerts on breakout signals, enabling traders to receive notifications for key zone crossings.
█ HOW TO USE
Add to Chart: Apply the indicator to your TradingView chart via the Pine Editor or Indicators menu.
Configure Settings:
- RSI Settings: Adjust RSI Length (default 14), Overbought Level (default 70), and Oversold Level (default 30) to tailor zone detection sensitivity—higher lengths smooth signals for longer-term analysis.
- Box Settings: Configure colors and transparency for overbought (red) and oversold (green) zones, including box transparency (default 90) and zone transparency (default 90).
- Signal Settings: Customize breakout signal colors (green for upward, red for downward) and enable/disable keeping boxes after RSI normalization.
Interpreting Signals:
- Upward Breakout Signal: A green triangle below the bar indicates a breakout, suggesting potential bullish momentum and trend continuation or reversal.
- Downward Breakout Signal: A red triangle above the bar indicates a breakout, suggesting potential bearish momentum.
- RSI Zones: If the price re-enters a zone after a breakout, it may signal a false breakout or consolidation; persistent zones can act as future support/resistance levels. Consolidation often occurs within these zones as the market seeks equilibrium.
- Use signals alongside other technical analysis tools for confirmation, such as moving averages (to confirm trend direction), Fibonacci levels (to identify key price zones), or volume indicators (to validate breakout strength). Analyze RSI zones on higher timeframes for stronger signals due to broader market context.
█ APPLICATIONS
- Momentum Trading: Use RSI zones as overbought/oversold filters. In an uptrend, look for buying opportunities on upward breakouts, and in a downtrend, on downward breakouts. Combining with MACD crossovers, Fibonacci levels, or pivot points enhances zone significance.
- Inter-Zone Trading: Utilize breakouts from one RSI zone and hold the position until reaching the next zone, which may act as a target level or reversal point.
█ NOTES
- Test the indicator across different timeframes and markets (stocks, forex, crypto) to optimize RSI length and levels for your trading style.
- For best results, use in trending markets where RSI extremes are more predictive; in ranging markets, additional filters are recommended to reduce false signals.
- Always combine with risk management; RSI zones alone do not guarantee reversals, and false breakouts may occur in low-liquidity environments.
Reversal Zones// This indicator identifies likely reversal zones above and below current price by aggregating multiple technical signals:
// • Prior Day High/Low
// • Opening Range (9:30–10:00)
// • VWAP ±2 standard deviations
// • 60‑minute Bollinger Bands
// It draws shaded boxes for each base level, then computes a single upper/lower reversal zone (closest level from combined signals),
// with configurable zone width based on the expected move (EM). Within those reversal zones, it highlights an inner “strike zone”
// (percentage of the box) to suggest optimal short-option strikes for credit spreads or iron condors.
// Additional features:
// • Optional Expected Move lines from the RTH open
// • 15‑minute RSI/Mean‑Reversion and Trend‑Day confluence flags displayed in a dashboard
// • Toggles to include/exclude each signal and adjust styling
// How to use:
// 1. Adjust inputs to select which levels to include and set the expected move parameters.
// 2. Reversal boxes (red above, green below) show zones where price is most likely to reverse.
// 3. Inner strike zones (darker shading) guide optimal short-strike placement.
// 4. Dashboard confirms whether mean-reversion or trend-day conditions are active.
// Customize colors and visibility in the settings panel. Enjoy disciplined, confluence-based trade entries!
TriAnchor Elastic Reversion US Market SPY and QQQ adaptedSummary in one paragraph
Mean-reversion strategy for liquid ETFs, index futures, large-cap equities, and major crypto on intraday to daily timeframes. It waits for three anchored VWAP stretches to become statistically extreme, aligns with bar-shape and breadth, and fades the move. Originality comes from fusing daily, weekly, and monthly AVWAP distances into a single ATR-normalized energy percentile, then gating with a robust Z-score and a session-safe gap filter.
Scope and intent
• Markets: SPY QQQ IWM NDX large caps liquid futures liquid crypto
• Timeframes: 5 min to 1 day
• Default demo: SPY on 60 min
• Purpose: fade stretched moves only when multi-anchor context and breadth agree
• Limits: strategy uses standard candles for signals and orders only
Originality and usefulness
• Unique fusion: tri-anchor AVWAP energy percentile plus robust Z of close plus shape-in-range gate plus breadth Z of SPY QQQ IWM
• Failure mode addressed: chasing extended moves and fading during index-wide thrusts
• Testability: each component is an input and visible in orders list via L and S tags
• Portable yardstick: distances are ATR-normalized so thresholds transfer across symbols
• Open source: method and implementation are disclosed for community review
Method overview in plain language
Base measures
• Range basis: ATR(length = atr_len) as the normalization unit
• Return basis: not used directly; we use rank statistics for stability
Components
• Tri-Anchor Energy: squared distances of price from daily, weekly, monthly AVWAPs, each divided by ATR, then summed and ranked to a percentile over base_len
• Robust Z of Close: median and MAD based Z to avoid outliers
• Shape Gate: position of close inside bar range to require capitulation for longs and exhaustion for shorts
• Breadth Gate: average robust Z of SPY QQQ IWM to avoid fading when the tape is one-sided
• Gap Shock: skip signals after large session gaps
Fusion rule
• All required gates must be true: Energy ≥ energy_trig_prc, |Robust Z| ≥ z_trig, Shape satisfied, Breadth confirmed, Gap filter clear
Signal rule
• Long: energy extreme, Z negative beyond threshold, close near bar low, breadth Z ≤ −breadth_z_ok
• Short: energy extreme, Z positive beyond threshold, close near bar high, breadth Z ≥ +breadth_z_ok
What you will see on the chart
• Standard strategy arrows for entries and exits
• Optional short-side brackets: ATR stop and ATR take profit if enabled
Inputs with guidance
Setup
• Base length: window for percentile ranks and medians. Typical 40 to 80. Longer smooths, shorter reacts.
• ATR length: normalization unit. Typical 10 to 20. Higher reduces noise.
• VWAP band stdev: volatility bands for anchors. Typical 2.0 to 4.0.
• Robust Z window: 40 to 100. Larger for stability.
• Robust Z entry magnitude: 1.2 to 2.2. Higher means stronger extremes only.
• Energy percentile trigger: 90 to 99.5. Higher limits signals to rare stretches.
• Bar close in range gate long: 0.05 to 0.25. Larger requires deeper capitulation for longs.
Regime and Breadth
• Use breadth gate: on when trading indices or broad ETFs.
• Breadth Z confirm magnitude: 0.8 to 1.8. Higher avoids fighting thrusts.
• Gap shock percent: 1.0 to 5.0. Larger allows more gaps to trade.
Risk — Short only
• Enable short SL TP: on to bracket shorts.
• Short ATR stop mult: 1.0 to 3.0.
• Short ATR take profit mult: 1.0 to 6.0.
Properties visible in this publication
• Initial capital: 25000USD
• Default order size: Percent of total equity 3%
• Pyramiding: 0
• Commission: 0.03 percent
• Slippage: 5 ticks
• Process orders on close: OFF
• Bar magnifier: OFF
• Recalculate after order is filled: OFF
• Calc on every tick: OFF
• request.security lookahead off where used
Realism and responsible publication
• No performance claims. Past results never guarantee future outcomes
• Fills and slippage vary by venue
• Shapes can move during bar formation and settle on close
• Standard candles only for strategies
Honest limitations and failure modes
• Economic releases or very thin liquidity can overwhelm mean-reversion logic
• Heavy gap regimes may require larger gap filter or TR-based tuning
• Very quiet regimes reduce signal contrast; extend windows or raise thresholds
Open source reuse and credits
• None
Strategy notice
Orders are simulated by TradingView on standard candles. request.security uses lookahead off where applicable. Non-standard charts are not supported for execution.
Entries and exits
• Entry logic: as in Signal rule above
• Exit logic: short side optional ATR stop and ATR take profit via brackets; long side closes on opposite setup
• Risk model: ATR-based brackets on shorts when enabled
• Tie handling: stop first when both could be touched inside one bar
Dataset and sample size
• Test across your visible history. For robust inference prefer 100 plus trades.
Puell Multiple Variants [OperationHeadLessChicken]Overview
This script contains three different, but related indicators to visualise Bitcoin miner revenue.
The classical Puell Multiple : historically, it has been good at signaling Bitcoin cycle tops and bottoms, but due to the diminishing rewards miners get after each halving, it is not clear how you determine overvalued and undervalued territories on it. Here is how the other two modified versions come into play:
Halving-Corrected Puell Multiple : The idea is to multiply the miner revenue after each halving with a correction factor, so overvalued levels are made comparable by a horizontal line across cycles. After experimentation, this correction factor turned out to be around 1.63. This brings cycle tops close to each other, but we lose the ability to see undervalued territories as a horizontal region. The third variant aims to fix this:
Miner Revenue Relative Strength Index (Miner Revenue RSI) : It uses RSI to map miner revenue into the 0-100 range, making it easy to visualise over/undervalued territories. With correct parameter settings, it eliminates the diminishing nature of the original Puell Multiple, and shows both over- and undervalued revenues correctly.
Example usage
The goal is to determine cycle tops and bottoms. I recommend using it on high timeframes, like monthly or weekly . Lower than that, you will see a lot of noise, but it could still be used. Here I use monthly as the example.
The classical Puell Multiple is included for reference. It is calculated as Miner Revenue divided by the 365-day Moving Average of the Miner Revenue . As you can see in the picture below, it has been good at signaling tops at 1,3,5,7.
The problems:
- I have to switch the Puell Multiple to a logarithmic scale
- Still, I cannot use a horizontal oversold territory
- 5 didn't touch the trendline, despite being a cycle top
- 9 touched the trendline despite not being a cycle top
Halving-Corrected Puell Multiple (yellow): Multiplies the Puell Multiple by 1.63 (a number determined via experimentation) after each halving. In the picture below, you can see how the Classical (white) and Corrected (yellow) Puell Multiples compare:
Advantages:
- Now you can set a constant overvalued level (12.49 in my case)
- 1,3,7 are signaled correctly as cycle tops
- 9 is correctly not signaled as a cycle top
Caveats:
- Now you don't have bottom signals anymore
- 5 is still not signaled as cycle top
Let's see if we can further improve this:
Miner Revenue RSI (blue):
On the monthly, you can see that an RSI period of 6, an overvalued threshold of 90, and an undervalued threshold of 35 have given historically pretty good signals.
Advantages:
- Uses two simple and clear horizontal levels for undervalued and overvalued levels
- Signaling 1,3,5,7 correctly as cycle tops
- Correctly does not signal 9 as a cycle top
- Signaling 4,6,8 correctly as cycle bottoms
Caveats:
- Misses two as a cycle bottom, although it was a long time ago when the Bitcoin market was much less mature
- In the past, gave some early overvalued signals
Usage
Using the example above, you can apply these indicators to any timeframe you like and tweak their parameters to obtain signals for overvalued/undervalued BTC prices
You can show or hide any of the three indicators individually
Set overvalued/undervalued thresholds for each => the background will highlight in green (undervalued) or red (overvalued)
Set special parameters for the given indicators: correction factor for the Corrected Puell and RSI period for Revenue RSI
Show or hide halving events on the indicator panel
All parameters and colours are adjustable
Supersonic Volatility & Momentum IndicatorChange/update the setting as per your trading requirements!
Advanced HMM - 3 States CompleteHidden Markov Model
Aconsistent challenge for quantitative traders is the frequent behaviour modification of financial
markets, often abruptly, due to changing periods of government policy, regulatory environment
and other macroeconomic effects. Such periods are known as market regimes. Detecting such
changes is a common, albeit difficult, process undertaken by quantitative market participants.
These various regimes lead to adjustments of asset returns via shifts in their means, variances,
autocorrelation and covariances. This impacts the effectiveness of time series methods that rely
on stationarity. In particular it can lead to dynamically-varying correlation, excess kurtosis ("fat
tails"), heteroskedasticity (volatility clustering) and skewed returns.
There is a clear need to effectively detect these regimes. This aids optimal deployment of
quantitative trading strategies and tuning the parameters within them. The modeling task then
becomes an attempt to identify when a new regime has occurred adjusting strategy deployment,
risk management and position sizing criteria accordingly.
A principal method for carrying out regime detection is to use a statistical time series tech
nique known as a Hidden Markov Model . These models are well-suited to the task since they
involve inference on "hidden" generative processes via "noisy" indirect observations correlated
to these processes. In this instance the hidden, or latent, process is the underlying regime state,
while the asset returns are the indirect noisy observations that are influenced by these states.
MAIN FEATURES OF THE INDICATOR
The "Advanced HMM - 3 States Complete" indicator is an advanced technical analysis tool that uses Hidden Markov Model (HMM) to identify three main market regimes: BULL, BEAR, and SIDEWAYS.
🎯 KEY FEATURES:
1. HMM-based Trend Detection
3 market states: Bull (0), Bear (1), Sideways (2)
Dynamic probabilities: Calculates probability for each state based on price data
Transition matrix: Models state transitions between regimes
2. Analytical Features
Price volatility: Log returns and standard deviation
Momentum: Rate of Change (ROC)
Volume: Volume ratio vs moving average
Data normalization: Standardizes features to common scale
3. Visual Trading Signals
text
📍 BUY Signals:
- Green upward triangle below bars
- "LONG" label in green
📍 SELL Signals:
- Red downward triangle above bars
- "SHORT" label in red
📍 EXIT Signals:
- Orange X marks when transitioning to sideways
4. Information Display
Probability table (top-right): Shows percentage for each state
State label: Current regime with probability percentages
Chart background color: Reflects dominant market state
5. Automated Alerts
Alerts when new Bull/Bear market detected
Alerts when market transitions to sideways
Configurable TradingView notifications
6. Customizable Parameters
pinescript
length: 100 // Lookback period
smoothing_period: 20 // Probability smoothing
volatility_threshold: 0.5 // Volatility threshold
💡 PRACTICAL APPLICATIONS:
Identify primary trends with quantified probabilities
Entry/exit signals based on state transitions
Risk management during sideways markets
Trend confirmation when combined with other indicators
This indicator is particularly useful for market regime analysis and identifying trend transition points using advanced statistical probability methods.
🔧 TECHNICAL IMPLEMENTATION:
Composite observation: Weighted combination of returns (40%), momentum (30%), and volatility (30%)
Gaussian emission probabilities: Different distributions for each state
Manual HMM updates: Avoids matrix computation limitations in Pine Script
Real-time smoothing: EMA applied to state probabilities
The indicator provides institutional-grade regime detection in a visually intuitive package suitable for both discretionary and systematic traders.
ICT Liquidity Sweep Asia/London 1 Trade per High & Low🧠 ICT Liquidity Sweep Asia/London — 1 Trade per High & Low
This strategy is inspired by the ICT (Inner Circle Trader) concepts of liquidity sweeps and market structure, focusing on the Asia and London sessions.
It automatically identifies liquidity grabs (sweeps) above or below key session highs/lows and enters trades with a fixed risk/reward ratio (RR).
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
⚙️ Core Logic
-Asia Session: 8:00 PM – 11:59 PM (New York time)
-London Session: 2:00 AM – 5:00 AM (New York time)
-The script marks the Asia High/Low and London High/Low ranges for each day.
-When the market sweeps above a session high → potential Short setup
-When the market sweeps below a session low → potential Long setup
-A trade is triggered when the confirmation candle closes in the opposite direction of the sweep (bearish after a high sweep, bullish after a low sweep).
-Only one trade per sweep type (1 per High, 1 per Low) is allowed per session.
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
📈 Risk Management
-Configurable Risk/Reward Target (default = 2:1)
-Configurable Position Size (number of contracts)
-Each trade uses a fixed Stop Loss (beyond the wick of the sweep) and a Take Profit calculated from the RR setting.
-All trades are automatically logged in the Strategy Tester with performance metrics.
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
💡 Features
✅ Visual session highlighting (Asia = Aqua, London = Orange)
✅ Automatic liquidity line plotting (session highs/lows)
✅ Entry & exit labels (optional visual display)
✅ Customizable RR and contract size
✅ Works on any instrument (ideal for indices, futures, or forex)
✅ Compatible with all timeframes (optimized for 1M–15M)
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
⚠️ Notes
-Best used on New York time-based charts.
-Designed for educational and backtesting purposes — not financial advice.
-Use as a foundation for further optimization (e.g., SMT confirmation, FVG filter, or time-based restrictions).
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
🧩 Recommended Use
Pair this with:
-ICT’s concepts like CISD (Change in State of Delivery) and FVGs (Fair Value Gaps)
-Higher timeframe liquidity maps
-Session bias or daily narrative filters
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
Author: jygirouard
Strategy Version: 1.3
Type: ICT Liquidity Sweep Automation
Timezone: America/New_York
Smooth Theil-SenI wanted to build a Theil-Sen estimator that could run on more than one bar and produce smoother output than the standard implementation. Theil-Sen regression is a non-parametric method that calculates the median slope between all pairs of points in your dataset, which makes it extremely robust to outliers. The problem is that median operations produce discrete jumps, especially when you're working with limited sample sizes. Every time the median shifts from one value to another, you get a step change in your regression line, which creates visual choppiness that can be distracting even though the underlying calculations are sound.
The solution I ended up going with was convolving a Gaussian kernel around the center of the sorted lists to get a more continuous median estimate. Instead of just picking the middle value or averaging the two middle values when you have an even sample size, the Gaussian kernel weights the values near the center more heavily and smoothly tapers off as you move away from the median position. This creates a weighted average that behaves like a median in terms of robustness but produces much smoother transitions as new data points arrive and the sorted list shifts.
There are variance tradeoffs with this approach since you're no longer using the pure median, but they're minimal in practice. The kernel weighting stays concentrated enough around the center that you retain most of the outlier resistance that makes Theil-Sen useful in the first place. What you gain is a regression line that updates smoothly instead of jumping discretely, which makes it easier to spot genuine trend changes versus just the statistical noise of median recalculation. The smoothness is particularly noticeable when you're running the estimator over longer lookback periods where the sorted list is large enough that small kernel adjustments have less impact on the overall center of mass.
The Gaussian kernel itself is a bell curve centered on the median position, with a standard deviation you can tune to control how much smoothing you want. Tighter kernels stay closer to the pure median behavior and give you more discrete steps. Wider kernels spread the weighting further from the center and produce smoother output at the cost of slightly reduced outlier resistance. The default settings strike a balance that keeps the estimator robust while removing most of the visual jitter.
Running Theil-Sen on multiple bars means calculating slopes between all pairs of points across your lookback window, sorting those slopes, and then applying the Gaussian kernel to find the weighted center of that sorted distribution. This is computationally more expensive than simple moving averages or even standard linear regression, but Pine Script handles it well enough for reasonable lookback lengths. The benefit is that you get a trend estimate that doesn't get thrown off by individual spikes or anomalies in your price data, which is valuable when working with noisy instruments or during volatile periods where traditional regression lines can swing wildly.
The implementation maintains sorted arrays for both the slope calculations and the final kernel weighting, which keeps everything organized and makes the Gaussian convolution straightforward. The kernel weights are precalculated based on the distance from the center position, then applied as multipliers to the sorted slope values before summing to get the final smoothed median slope. That slope gets combined with an intercept calculation to produce the regression line values you see plotted on the chart.
What this really demonstrates is that you can take classical statistical methods like Theil-Sen and adapt them with signal processing techniques like kernel convolution to get behavior that's more suited to real-time visualization. The pure mathematical definition of a median is discrete by nature, but financial charts benefit from smooth, continuous lines that make it easier to track changes over time. By introducing the Gaussian kernel weighting, you preserve the core robustness of the median-based approach while gaining the visual smoothness of methods that use weighted averages. Whether that smoothness is worth the minor variance tradeoff depends on your use case, but for most charting applications, the improved readability makes it a good compromise.
Hyper SAR Reactor Trend StrategyHyperSAR Reactor Adaptive PSAR Strategy
Summary
Adaptive Parabolic SAR strategy for liquid stocks, ETFs, futures, and crypto across intraday to daily timeframes. It acts only when an adaptive trail flips and confirmation gates agree. Originality comes from a logistic boost of the SAR acceleration using drift versus ATR, plus ATR hysteresis, inertia on the trail, and a bear-only gate for shorts. Add to a clean chart and run on bar close for conservative alerts.
Scope and intent
• Markets: large cap equities and ETFs, index futures, major FX, liquid crypto
• Timeframes: one minute to daily
• Default demo: BTC on 60 minute
• Purpose: faster yet calmer PSAR that resists chop and improves short discipline
• Limits: this is a strategy that places simulated orders on standard candles
Originality and usefulness
• Novel fusion: PSAR AF is boosted by a logistic function of normalized drift, trail is monotone with inertia, entries use ATR buffers and optional cooldown, shorts are allowed only in a bear bias
• Addresses false flips in low volatility and weak downtrends
• All controls are exposed in Inputs for testability
• Yardstick: ATR normalizes drift so settings port across symbols
• Open source. No links. No solicitation
Method overview
Components
• Adaptive AF: base step plus boost factor times logistic strength
• Trail inertia: one sided blend that keeps the SAR monotone
• Flip hysteresis: price must clear SAR by a buffer times ATR
• Volatility gate: ATR over its mean must exceed a ratio
• Bear bias for shorts: price below EMA of length 91 with negative slope window 54
• Cooldown bars optional after any entry
• Visual SAR smoothing is cosmetic and does not drive orders
Fusion rule
Entry requires the internal flip plus all enabled gates. No weighted scores.
Signal rule
• Long when trend flips up and close is above SAR plus buffer times ATR and gates pass
• Short when trend flips down and close is below SAR minus buffer times ATR and gates pass
• Exit uses SAR as stop and optional ATR take profit per side
Inputs with guidance
Reactor Engine
• Start AF 0.02. Lower slows new trends. Higher reacts quicker
• Max AF 1. Typical 0.2 to 1. Caps acceleration
• Base step 0.04. Typical 0.01 to 0.08. Raises speed in trends
• Strength window 18. Typical 10 to 40. Drift estimation window
• ATR length 16. Typical 10 to 30. Volatility unit
• Strength gain 4.5. Typical 2 to 6. Steepness of logistic
• Strength center 0.45. Typical 0.3 to 0.8. Midpoint of logistic
• Boost factor 0.03. Typical 0.01 to 0.08. Adds to step when strength rises
• AF smoothing 0.50. Typical 0.2 to 0.7. Adds inertia to AF growth
• Trail smoothing 0.35. Typical 0.15 to 0.45. Adds inertia to the trail
• Allow Long, Allow Short toggles
Trade Filters
• Flip confirm buffer ATR 0.50. Typical 0.2 to 0.8. Raise to cut flips
• Cooldown bars after entry 0. Typical 0 to 8. Blocks re entry for N bars
• Vol gate length 30 and Vol gate ratio 1. Raise ratio to trade only in active regimes
• Gate shorts by bear regime ON. Bear bias window 54 and Bias MA length 91 tune strictness
Risk
• TP long ATR 1.0. Set to zero to disable
• TP short ATR 0.0. Set to 0.8 to 1.2 for quicker shorts
Usage recipes
Intraday trend focus
Confirm buffer 0.35 to 0.5. Cooldown 2 to 4. Vol gate ratio 1.1. Shorts gated by bear regime.
Intraday mean reversion focus
Confirm buffer 0.6 to 0.8. Cooldown 4 to 6. Lower boost factor. Leave shorts gated.
Swing continuation
Strength window 24 to 34. ATR length 20 to 30. Confirm buffer 0.4 to 0.6. Use daily or four hour charts.
Properties visible in this publication
Initial capital 10000. Base currency USD. Order size Percent of equity 3. Pyramiding 0. Commission 0.05 percent. Slippage 5 ticks. Process orders on close OFF. Bar magnifier OFF. Recalculate after order filled OFF. Calc on every tick OFF. No security calls.
Realism and responsible publication
No performance claims. Past results never guarantee future outcomes. Shapes can move while a bar forms and settle on close. Strategies execute only on standard candles.
Honest limitations and failure modes
High impact events and thin books can void assumptions. Gap heavy symbols may prefer longer ATR. Very quiet regimes can reduce contrast and invite false flips.
Open source reuse and credits
Public domain building blocks used: PSAR concept and ATR. Implementation and fusion are original. No borrowed code from other authors.
Strategy notice
Orders are simulated on standard candles. No lookahead.
Entries and exits
Long: flip up plus ATR buffer and all gates true
Short: flip down plus ATR buffer and gates true with bear bias when enabled
Exit: SAR stop per side, optional ATR take profit, optional cooldown after entry
Tie handling: stop first if both stop and target could fill in one bar
ATR Gauge - Audiophile StyleThe ATR Gauge - Audiophile Style indicator is a custom visualization tool. It's designed to give you a quick, retro-inspired snapshot of market volatility using the Average True Range (ATR) metric. Think of it as a dashboard widget styled like the VU meters on old-school audiophile equipment (e.g., vintage stereo amps from brands like McIntosh or Marantz)—simple, elegant, and functional. It sits in one of the corners of your chart and helps you gauge how "hot" or "cool" the current price action is compared to recent levels.
Why This Gauge?: Standard ATR plots as a line on your chart, but this turns it into a visual "meter" focused on the last 24 hours. It's like a speedometer for volatility—quick to read at a glance. Useful for day traders, scalpers, or anyone monitoring intraday risk without cluttering the main chart.
RSI Divergence Strategy v6 What this does
Detects regular and hidden divergences between price and RSI using confirmed RSI pivots. Adds RSI@pivot entry gates, a normalized strength + volume filter, optional volume gate, delayed entries, and transparent risk management with rigid SL and activatable trailing. Visuals are throttled for clarity and include a gap-free horizontal RSI gradient.
How it works (simple)
🧮 RSI is calculated on your selected source/period.
📌 RSI pivots are confirmed with left/right lookbacks (lbL/lbR). A pivot becomes final only after lbR bars; before that, it can move (expected).
🔎 The latest confirmed pivot is compared against the previous confirmed pivot within your bar window:
• Regular Bullish = price lower low + RSI higher low
• Hidden Bullish = price higher low + RSI lower low
• Regular Bearish = price higher high + RSI lower high
• Hidden Bearish = price lower high + RSI higher high
💪 Each divergence gets a strength score that multiplies price % change, RSI change, and a volume ratio (Volume SMA / Baseline Volume SMA).
• Set Min divergence strength to filter tiny/noisy signals.
• Turn on the volume gate to require volume ratio ≥ your threshold (e.g., 1.0).
🎯 RSI@pivot gating:
• Longs only if RSI at the bullish pivot ≤ 30 (default).
• Shorts only if RSI at the bearish pivot ≥ 70 (default).
⏱ Entry timing:
• Immediate: on divergence confirm (delay = 0).
• Delayed: after N bars if RSI is still valid.
• RSI-only mode: ignore divergences; use RSI thresholds only.
🛡 Risk:
• Rigid SL is placed from average entry.
• Trailing activates only after unrealized gain ≥ threshold; it re-anchors on new highs (long) or new lows (short).
What’s NEW here (vs. the reference) — and why you may care
• Improved pivots + bar window → fewer early/misaligned signals; cleaner drawings.
• RSI@pivot gates → entries aligned with true oversold/overbought at the exact decision bar.
• Normalized strength + volume gate → ignore weak or low-volume divergences.
• Delayed entries → require the signal to persist N bars if you want more confirmation.
• Rigid SL + activatable trailing → trailing engages only after a cushion, so it’s less noisy.
• Clutter control + gradient → readable chart with a smooth RSI band look.
Suggested starting values (clear ranges)
• RSI@pivot thresholds: LONG ≤ 30 (oversold), SHORT ≥ 70 (overbought).
• Min divergence strength:
0.0 = off
3–6 = moderate filter
7–12 = strict filter for noisy LTFs
• Volume gate (ratio):
1.0 = at least baseline volume
1.2–1.5 = strong-volume only (fewer but cleaner signals)
• Pivot lookbacks:
lbL 1–2, lbR 3–4 (raise lbR to confirm later and reduce noise)
• Bar window (between pivots):
Min 5–10, Max 30–60 (increase Min if you see micro-pivots; increase Max for wider structures)
• Risk:
Rigid SL 2–5% on liquid majors; 5–10% on higher-volatility symbols
Trailing activation 1–3%, trailing 0.5–1.5% are common intraday starts
Plain-text examples
• BTCUSDT 1h → RSI 9, lbL 1, lbR 3, Min strength 5.0, Volume gate 1.0, SL 4.5%, Trail on 2.0%, Trail 1.0%.
• SPY 15m → RSI 8, lbL 1, lbR 3, Min strength 7.0, Volume gate 1.2, SL 3.0%, Trail on 1.5%, Trail 0.8%.
• EURUSD 4h → RSI 14, lbL 2, lbR 4, Min strength 4.0, Volume gate 1.0, SL 2.5%, Trail on 1.0%, Trail 0.5%.
Notes & limitations
• Pivot confirmation means the newest candidate pivot can move until lbR confirms it (expected).
• Results vary by timeframe/symbol/settings; always forward-test.
• Educational tool — no performance or profit claims.
Credits
• RSI by J. Welles Wilder Jr. (1978).
• Reference divergence script by eemani123:
• This version by tagstrading 2025 adds: improved pivot engine, RSI@pivot gating, normalized strength + optional volume gate, delayed entries, rigid SL and activatable trailing, and a gap-free RSI gradient.
The Vishnu Zone Ver 2 by Dr. Sudhir Khollam## 📜 **The Vishnu Zone — Trade When the Brahma Zone Ends**
**Author:** Dr. Sudhir Khollam (SALSA© Method of Astrology & Market Psychology)
**Category:** Volatility Phase Detection / Bollinger Band Expansion Analysis
---
### 🔶 **Concept Overview**
In the **SALSA© Market Philosophy**, every market phase follows a cosmic rhythm —
* **Brahma Phase** represents *creation and expansion* (high volatility and strong directional movement).
* **Vishnu Phase** represents *maintenance and stability* (where expansion cools down and balanced opportunities appear).
**“The Vishnu Zone”** indicator identifies the exact moments when the **Brahma Phase ends** — signaling that the expansion has completed and the market is likely to enter a more stable, tradable state.
This is a **precision-timing indicator** that helps traders avoid entering at the end of impulsive phases and instead prepare for equilibrium-based trades (mean reversion, range setups, or steady trends).
---
### ⚙️ **How It Works**
The indicator measures **Bollinger Band Width (BBW)** to quantify expansion and contraction in volatility.
1. It calculates the **adaptive expansion threshold** using the average BBW over a rolling lookback period.
2. When the current BBW **drops below** this adaptive threshold **after being above it**, the script marks it as the **end of the Brahma Phase**.
3. This moment is shown visually as:
* 🕉 **“Vishnu” label** above the candle
* A **horizontal dotted line** extending for several bars
Together, these mark a **Vishnu Zone**, where the market transitions from expansion to consolidation — an ideal time for stabilization or entry planning.
---
### 📊 **Inputs & Settings**
| Parameter | Description |
| ---------------------------------- | ------------------------------------------------------------------------------ |
| **Bollinger Band Length** | The number of bars used for SMA and standard deviation (default 20). |
| **Bollinger Multiplier** | Determines the width of Bollinger Bands (default 2.0). |
| **Adaptive Lookback Period** | Rolling window to calculate the mean BBW for dynamic adjustment (default 150). |
| **Expansion Multiplier** | Multiplies the mean BBW to define the expansion threshold (default 1.35). |
| **Horizontal Line Extension Bars** | Number of bars to extend the Vishnu Zone line into the future (default 40). |
| **Show End-of-Brahma Labels?** | Toggle 🕉 labels on/off. |
| **Show Horizontal Lines?** | Toggle Vishnu Zone lines on/off. |
---
### 🔔 **Alerts**
When the **Brahma Phase ends**, the indicator triggers an alert:
> *“Brahma Phase Ends, Vishnu has taken over.”*
This helps traders receive real-time notification of volatility contraction and possible entry zones.
---
### 🧠 **Best Practices**
* Works effectively on **5-minute to 1-hour timeframes** for intraday trading.
* Best paired with **momentum or volume filters** to confirm trend exhaustion.
* Avoid entering during rapid expansion (Brahma phase). Wait for a Vishnu signal to ensure market stabilization.
---
### 🌌 **Philosophical Interpretation (SALSA© Principle)**
Just as Vishnu sustains the universe after Brahma’s creation, the market too enters a **maintenance phase** after every burst of expansion.
Recognizing this shift allows traders to align with **cosmic rhythm and price psychology**, not just technical metrics.
---
### 🧩 **Summary**
✅ Detects when expansion volatility ends
✅ Marks transition zones between impulsive and stable phases
✅ Sends real-time alerts
✅ Adaptive and self-adjusting across markets and assets
✅ Simple, clean visualization — ideal for disciplined trading
---
### ⚡ **Use Case**
Perfect for traders who:
* Prefer **low-risk entries** after volatility spikes
* Trade **mean reversion**, **range breakouts**, or **volatility collapses**
* Believe in the **cyclic nature of market energy**
---
4-Hour Range Scalping [v6.3]User Guide: 4-Hour Range Scalping Strategy
Hello! Here is the guide for the Pine Script strategy. Please read it carefully to get the best results.
📈 This script automates the "4-Hour Range Scalping Strategy" from the video.
The main idea is that the first four hours of a major trading day (like New York) set up a "trap zone." The strategy waits for the price to break out of this zone and then fail, giving us a signal that the breakout was false and the price is likely to reverse.
Here’s the simple logic:
Define the Range: It precisely calculates the highest high and lowest low during the first four hours of the selected trading session (e.g., 00:00 to 04:00 New York Time).
Wait for a Breakout: It then monitors the 5-minute chart for a price breakout where a candle fully closes outside of this established range.
Identify the Reversal: The trade trigger occurs when the price fails to continue its breakout and a subsequent 5-minute candle closes back inside the range. This signals a potential reversal or "failed breakout."
Execute the Trade:
]A Short (Sell) trade is triggered after a failed breakout above the range high.
A Long (Buy) trade is triggered after a failed breakout below the range low.
Manage the Risk: The Stop Loss is automatically placed at the peak (for shorts) or trough (for longs) of the breakout move, and the Take Profit is set to a default 2:1 Risk/Reward Ratio.
How to Use the Script (Step-by-Step) ⚙️
Follow these instructions to get it running perfectly.
1. Set Your Chart Timeframe This is the most important step. The strategy is designed to run on a 5-minute (5m) chart. Open your TradingView chart and make sure the timeframe is set to "5m".
2. Add the Script to Your Chart Open the Pine Editor tab at the bottom of TradingView, paste the entire script, and click the "Add to chart" button.
3. Configure the Settings On your chart, find the strategy's name (e.g., "4-Hour Range Scalping ") and click the gear icon ⚙️ to open its settings.
Trading Session: Choose the session for the range. New York is the default and the one from the video.
Risk/Reward Ratio: The default is 2.0, meaning your potential profit is twice your potential loss. You can adjust this to test other targets.
Backtesting Period: To see how the strategy performed on all historical data, go to the "Strategy Tester" panel, click its own gear icon ⚙️, and uncheck the boxes for "Start Date" and "End Date."
4. Understand the Visuals on Your Chart
Blue Background Area: This is the 4-hour calculation window. The script is identifying the day's high and low during this time. No trades will ever happen here.
Red Line (Range High): The highest price of the 4-hour window. This is the upper boundary of the "trap zone."
Green Line (Range Low): The lowest price of the 4-hour window. This is the lower boundary.
Green Triangle (▲): Shows where a Long (Buy) trade was entered.
Red Triangle (▼): Shows where a Short (Sell) trade was entered.
A Very Important Note on Timezones 🕒
This is critical for you in the Philippines (PHT).
The script is based on the New York session, which is 12 hours behind you. Your TradingView chart will still show your local time, but the script works on NY time in the background.
The New York "day" begins at 12:00 PM (Noon) your time.
The script's blue calculation window will be from 12:00 PM to 4:00 PM your local time.
The red and green range lines will appear on your chart only after 4:00 PM your time.
So, if you look at your chart in the morning or early afternoon, you will not see today's range yet. This is normal! The script is just waiting for the New York session to start.
How to Set Up Trade Alerts 🔔
You can have TradingView send you a notification whenever the script enters a trade.
Click the "Alert" button (looks like a clock) in the right-hand toolbar of TradingView.
In the "Condition" dropdown, select the name of the script (e.g., "4-Hour Range Scalping...").
You will then see two options: "Long Signal" and "Short Signal".
Select one (e.g., "Long Signal") and configure how you want to be notified (e.g., "Notify on app").
Click "Create". Repeat the process to create an alert for the other signal.
⚠️ Important Disclosure
For Educational and Research Purposes Only.
This script and all accompanying information are provided for educational and research purposes only. The strategy demonstrated is a technical concept and should not be misconstrued as financial, investment, legal, or tax advice.
Trading financial markets involves substantial risk and is not suitable for every investor. There is a possibility that you could sustain a loss of some or all of your initial investment. Therefore, you should not invest money that you cannot afford to lose.
Past performance is not indicative of future results. The backtesting results shown by this script are historical and do not guarantee future performance. Market conditions are constantly changing.
By using this script, you acknowledge that you are solely responsible for any and all trading decisions you make. You should conduct your own thorough research and, if necessary, seek advice from an independent financial advisor before making any investment decisions. The creators of this script assume no liability for any of your trading results.
Trend Pivot Retracements [TradeEasy]▶ OVERVIEW
Trend Pivot Retracements identifies market trend direction using a Donchian-style channel and dynamically highlights retracement zones during trending conditions. It calculates the percentage pullbacks from recent highs and lows, plots labeled zones with varying intensity, and visually connects key retracement pivots. The indicator also emphasizes price proximity to trend boundaries by dynamically adjusting the thickness of plotted trend bands.
▶ TREND DETECTION & BAND STRUCTURE
The indicator determines the current trend by checking for new 50-bar extremes:
Uptrend: If a new highest high is made, the trend is considered bullish.
Downtrend: If a new lowest low is made, the trend is considered bearish.
Uptrend Band: Plots the 50-bar lowest low as a trailing support level.
Downtrend Band: Plots the 50-bar highest high as a trailing resistance level.
Thickness Variation: The thickness of the band increases the further price moves from it, indicating overextension.
▶ RETRACEMENT LABELING SYSTEM
During a trend, the indicator monitors pivot points in the opposite direction to measure retracements:
Bullish Retracement:
Triggered when a pivot low forms during an uptrend.
Measures % pullback from the most recent swing high (searched up to 20 bars back).
Plots a bold horizontal line at the low and a dashed diagonal from the previous swing high.
Adds a “-%” label above the low; intensity is based on recent 50 pullbacks.
Bearish Retracement:
Triggered when a pivot high forms during a downtrend.
Measures % pullback from the previous swing low (up to 20 bars back).
Plots a bold horizontal line at the high and a dashed diagonal from the prior swing low.
Adds a “%” label below the high with gradient color based on the past 50 extremes.
▶ PIVOT CONNECTION LINES
Each retracement includes a visual connector:
A diagonal dashed line linking the swing extreme (20 bars back) to the retracement point.
This line visually traces the path of price retreat within the trend.
Helps traders understand where the retracement originated and how steep it was.
▶ TREND SWITCH SIGNALS
When trend direction changes:
A diamond marker is plotted on the new pivot confirming the trend shift.
Green diamonds signal new bullish trends at fresh lows.
Magenta diamonds signal new bearish trends at fresh highs.
▶ COLOR INTENSITY & CONTEXTUAL AWARENESS
To help interpret the magnitude of retracements:
The % labels are color-coded using a gradient scale that references the max of the last 50 pullbacks.
Stronger pullbacks result in deeper color intensity, signaling more significant corrections.
Trend bands also use standard deviation normalization to adjust line thickness based on how far price has moved from the band.
This creates a visual cue for potential exhaustion or volatility extremes.
▶ USAGE
Trend Pivot Retracements is a powerful tool for traders who want to:
Identify trend direction and contextual pullbacks within those trends.
Spot key retracement points that may serve as entry opportunities or reversal signals.
Use visual retracement angles to understand market pressure and trend maturity.
Read dynamic band thickness as an alert for price stretch, potential mean reversion, or breakout setups.
▶ CONCLUSION
Trend Pivot Retracements gives traders a clean, visually expressive way to monitor trending markets, while capturing and labeling meaningful retracements. With adaptive color intensity, diagonal connectors, and smart trend switching, it enhances situational awareness and provides immediate clarity on trend health and pullback strength.
Previous TPOIndicator Summary
This Pine Script indicator, "Previous TPO," is designed to calculate and display five key price levels from the previous trading day's market activity. It uses a 30-minute TPO (Time Price Opportunity) profile, which is a method of organizing price by time to find areas of high and low activity.
The five levels it plots on the current day are:
1. Previous Value Area High (VAH)
2. Previous Value Area Low (VAL)
3. Previous Point of Control (POC)
4. Previous Initial Balance High (IBH)
5. Previous Initial Balance Low (IBL)
The script is built to be efficient, running its main calculation only once at the beginning of each new day. It also includes an automatic line management system to delete old lines, preventing the "Too many lines" error and keeping the chart clean.
How the Code Works
1. Data Collection: At the start of a new day (00:00), the script looks back at the chart's history. It uses request.security to access 30-minute bar data.
2. Collector Loop: It then loops backward, bar by bar, to find and store 48 unique 30-minute High/Low data points, which represents the full 24-hour range of the previous day.
3. TPO Profile: With this 30-minute data, it builds a TPO profile. It divides the previous day's price range into small bins (price levels) and counts how many 30-minute periods "touched" each price bin.
4. Level Calculation:
o POC: It finds the price bin with the highest TPO count (the most traded price) and sets it as the Point of Control.
o VAH/VAL: It starts at the POC and expands outward, adding the next-most-traded price bins until 70% (or the user-defined percentage) of the day's TPOs are included. The highest and lowest prices of this range are the Value Area High and Value Area Low.
o IBH/IBL: It identifies the high and low of the first hour (the first two 30-minute bars) of the previous day to set the Initial Balance High and Initial Balance Low.
5. Drawing: The script draws these five levels as horizontal lines across the current trading day, providing a constant reference.
6. Line Management: It keeps track of all lines in an array. When the total number of lines exceeds the user's limit (e.g., 50 days * 5 lines = 250), it automatically deletes the oldest lines from the chart.
Usefulness for Trading
This indicator provides a powerful framework for intraday traders by contextualizing the current day's price action against the previous day's "auction."
• Key Support/Resistance: The VAH, VAL, and POC act as significant support and resistance lev-els. Price reacting at these levels can signal mean reversion, while acceptance beyond them can signal a trend or expansion day.
• Value Area as Context: Trading inside the previous day's value area (between VAH and VAL) is often seen as "balanced" or "range-bound" trading. Trading outside of it is "unbalanced" or "trending."
• POC as a "Magnet": The POC, being the area of highest volume/time, often acts as a "magnet" or "center of gravity" for price.
• Opening Range: The Initial Balance (IB) levels show the opening range. A breakout from this range is often a key signal for the day's initial direction.
• 80% Rule: The script contains (currently commented-out) setup logic for the "80% Rule." This is a specific Market Profile strategy where:
1. The market opens inside the previous day's Value Area.
2. The Initial Balance fails to extend outside the VA (e.g., in a short setup, the IB high stays below the VAH).
3. This setup suggests an 80% probability that the price will rotate and test the other side of the Value Area (e.g., test the VAL).
Publication and restrictions
This script is published under the Mozilla Public Licence 2.0 (MPL 2.0) and is therefore suitable for publi-cation as an open source indicator on TradingView.
Timeframe limitation: The indicator is designed for intraday timeframes. Timeframes below 10 minutes do not work and lead to an error. Recommended time frame 30 minutes.
It will not work correctly on:
Time frame under 10 minutes: The data collection loop (max_bars_to_check = 3000) is not large enough to collect the bars required for a full day on a 5-minute chart or smaller.
High time frames (e.g. 1H, 4H, Daily): The script's logic is based on a chart timeframe 30-minute data that it requests. If higher time frames are selected, the script works but the zones are no longer correct or become irrelevant.
Trend Following Reflectometry🧭 Trend Following Reflectometry (TFR)
Author: Stef Jonker
Version: Pine Script® v6
The Trend Following Reflectometry (TFR) indicator translates market behavior into the language of impedance and signal reflection theory, providing a unique way to measure trend strength, stability, and purity.
🧩 Summary
Trend Following Reflectometry acts as a trend-quality meter, helping traders identify when a trend is strong, efficient, and worth following — or when the market is too noisy to trust.
It blends physics-inspired logic with practical trading insight, offering both a directional oscillator and a trend stability filter in one tool.
⚙️ Concept
Inspired by electrical impedance matching, this tool compares the market’s characteristic impedance (Z₀) — its natural volatility-to-price behavior — with the load impedance (Zₗ), representing current trend momentum.
The interaction between these two produces a reflection coefficient (Gamma) and a VSWR ratio, which reveal how efficiently market trends are transmitting energy (moving smoothly) versus reflecting noise (becoming unstable).
📊 Core Components
Z₀ (Characteristic Impedance): Market baseline, derived from ATR and SMA.
Zₗ (Load Impedance): Trend momentum based on fast and slow EMAs.
Γ (Gamma – Reflection Coefficient): Measures the mismatch between Z₀ and Zₗ.
VSWR (Voltage Standing Wave Ratio): Quantifies trend purity — lower = cleaner trend.
Impedance Oscillator: Combines momentum and reflection to produce directional bias.
⚡ Gamma & VSWR Interpretation
Gamma (Γ) represents the reflection coefficient — how much of the market’s trend energy is being reflected instead of transmitted.
When Gamma is low, the market trend is smooth and efficient, moving with little resistance.
When Gamma is high, the market becomes unstable or overextended, signaling potential turbulence, exhaustion, or reversal pressure.
VSWR (Voltage Standing Wave Ratio) measures trend purity — how clean or distorted the current trend is.
A low VSWR indicates a well-aligned, steady trend that’s likely to continue smoothly.
A high VSWR suggests an unbalanced or noisy market, where trends may struggle to sustain or could soon reverse.
Together, Gamma and VSWR help identify how well the market’s current momentum aligns with its natural behavior — whether the trend is stable and efficient or reflecting instability beneath the surface.
RSI to Price Projection PanelThis indicator calculates the current RSI based on the closing price and projects estimated prices for user-defined RSI target levels. Results are displayed in a table at the top-right corner of the chart.
#MS Yearly Opening Range (First X Days)The first 10 trading days of the year are important for the remainder of the year. If the price is held below the lowest price in the first 10 trading days, then consider that BEARISH. If the price is above the highest price of the first 10 trading days then the instrument has a BULLISH Bias.
EMA Crossover Signals [LummiCrypto]Handsome, just turn on the buy and sell alerts.
English Instruction
How to Use the EMA Crossover Signals Indicator
This TradingView Pine Script generates BUY and SELL signals based on the crossover of two Exponential Moving Averages (EMAs) with user-selectable lengths (9, 20, 50, 100, or 200). BUY signals occur when the first EMA crosses above the second EMA, and SELL signals occur when the first EMA crosses below the second EMA. Signals are visualized as tiny green triangles (BUY) below the bar and red triangles (SELL) above the bar. Alerts are set up using alertcondition() for compatibility with Telegram notifications.
1. Add the Script to TradingView
Open TradingView and go to the Pine Editor (bottom of the screen).
Copy and paste the Pine Script into the editor.
Click “Add to Chart” to apply the indicator to your chart.
2. Configure EMA Lengths
Double-click the indicator name (“EMA Crossover Signals”) on the chart to open its settings.
In the settings, select the “First EMA Length” and “Second EMA Length” from the dropdown menus. Options are 9, 20, 50, 100, or 200.
Note: Choose different lengths for the two EMAs (e.g., 9 and 20) to ensure crossovers can occur. Setting both to the same length will prevent signals.
Click “OK” to save the settings.
3. Set Up Alerts in TradingView
Click the “Alert” button (bell icon) at the top of TradingView.
In the alert creation window:
Select “EMA Crossover Signals” as the condition.
Choose either “BUY Signal” or “SELL Signal” from the condition dropdown.
Keep the default message (e.g., “EMA Crossover: BUY Signal at {{close}}”) or customize it if needed.
Set the frequency to “Once Per Bar Close” to avoid duplicate alerts.
Name the alert, e.g., “EMA Buy Alert” or “EMA Sell Alert”.
Repeat the process to create separate alerts for BUY and SELL signals if desired.
Click “Create” to activate the alert.
4. Connect Alerts to Telegram
To send BUY and SELL signals to Telegram, you need to link TradingView alerts to a Telegram bot or channel. Here are the options:
Option 1: Webhook Setup
Create a Telegram bot using BotFather in Telegram and obtain the bot token.
Set up a webhook server (e.g., using Python, Node.js, or a service like Heroku) to receive TradingView alerts and forward them to Telegram.
In the TradingView alert settings, enable “Webhook URL” and enter your server’s URL (e.g., your-server.com).
Configure your server to send the alert message to Telegram using the Telegram Bot API (e.g., api.telegram.org).
Option 2: Third-Party Service
Use a service like Zapier or IFTTT to connect TradingView alerts to Telegram.
Set up a zap with TradingView as the trigger (via webhook) and Telegram as the action to send messages to your chat or channel.
Follow the service’s instructions to link your Telegram bot and specify the destination chat or channel.
Option 3: TradingView’s Telegram Integration (if available)
If TradingView offers direct Telegram integration in your region, follow their official guide to link your Telegram account and configure alerts to send messages directly.
5. Test the Alerts
Create test alerts for both BUY and SELL signals to ensure they work correctly.
Verify that messages (e.g., “EMA Crossover: BUY Signal at 50000”) appear in your Telegram chat or channel.
Check that the signals (green triangles for BUY, red triangles for SELL) appear correctly on the chart.
Инструкция на русском
Как использовать индикатор EMA Crossover Signals
Этот Pine Script для TradingView генерирует сигналы на покупку (BUY) и продажу (SELL) на основе пересечения двух экспоненциальных скользящих средних (EMA) с длинами, выбираемыми пользователем (9, 20, 50, 100 или 200). Сигнал BUY появляется, когда первая EMA пересекает вторую EMA снизу вверх, а сигнал SELL — когда первая EMA пересекает вторую EMA сверху вниз. Сигналы отображаются в виде маленьких зеленых треугольников (BUY) под свечой и красных треугольников (SELL) над свечой. Для уведомлений в Telegram используются alertcondition().
1. Добавление скрипта в TradingView
Откройте TradingView и перейдите в редактор Pine (внизу экрана).
Скопируйте и вставьте Pine Script в редактор.
Нажмите «Добавить на график», чтобы применить индикатор.
2. Настройка длин EMA
Дважды щелкните по названию индикатора («EMA Crossover Signals») на графике, чтобы открыть настройки.
В настройках выберите «First EMA Length» (Длина первой EMA) и «Second EMA Length» (Длина второй EMA) из выпадающих меню. Варианты: 9, 20, 50, 100, 200.
Важно: Выберите разные длины для двух EMA (например, 9 и 20), чтобы сигналы пересечения были возможны. Если выбрать одинаковые длины, сигналы не будут генерироваться.
Нажмите «ОК», чтобы сохранить настройки.
3. Настройка алертов в TradingView
Нажмите на кнопку «Алерт» (значок колокольчика) вверху TradingView.
В окне создания алерта:
Выберите «EMA Crossover Signals» в качестве условия.
Выберите «BUY Signal» или «SELL Signal» из выпадающего списка условий.
Оставьте сообщение по умолчанию (например, «EMA Crossover: BUY Signal at {{close}}») или настройте его по желанию.
Установите частоту «Только при закрытии бара», чтобы избежать дублирования алертов.
Задайте имя алерта, например, «EMA Buy Alert» или «EMA Sell Alert».
Повторите процесс, чтобы создать отдельные алерты для сигналов BUY и SELL, если нужно.
Нажмите «Создать», чтобы активировать алерт.
4. Подключение алертов к Telegram
Чтобы отправлять сигналы BUY и SELL в Telegram, необходимо связать алерты TradingView с ботом или каналом Telegram. Варианты:
Вариант 1: Настройка вебхука
Создайте бота в Telegram с помощью BotFather и получите токен бота.
Настройте сервер вебхука (например, с использованием Python, Node.js или сервиса Heroku), чтобы принимать алерты от TradingView и отправлять их в Telegram.
В настройках алерта TradingView включите «Webhook URL» и укажите URL вашего сервера (например, your-server.com).
Настройте сервер для отправки сообщений в Telegram через Telegram Bot API (например, api.telegram.org).
Вариант 2: Сторонний сервис
Используйте сервисы, такие как Zapier или IFTTT, для связи алертов TradingView с Telegram.
Настройте задачу (zap), где TradingView будет триггером (через вебхук), а Telegram — действием для отправки сообщений в ваш чат или канал.
Следуйте инструкциям сервиса для подключения бота Telegram и указания чата или канала.
Вариант 3: Прямая интеграция TradingView с Telegram (если доступно)
Если TradingView поддерживает прямую интеграцию с Telegram в вашем регионе, следуйте их официальной инструкции для подключения вашего аккаунта Telegram и настройки отправки сообщений.
5. Тестирование алертов
Создайте тестовые алерты для сигналов BUY и SELL, чтобы убедиться, что они работают корректно.
Проверьте, что сообщения (например, «EMA Crossover: BUY Signal at 50000») появляются в вашем чате или канале Telegram.
Убедитесь, что сигналы (зеленые треугольники для BUY, красные треугольники для SELL) корректно отображаются на графике.
Gold–Bitcoin Correlation (Offset Model) by KManus88This indicator analyzes the correlation between Gold (XAU/USD) and Bitcoin (BTC/USD) using a time-offset model adjustable by the user.
The goal is to detect cyclical leads or lags between both assets, highlighting how capital flows into Gold may precede or follow movements in the crypto market.
Key Features:
Dynamic correlation calculation between Gold and Bitcoin.
Adjustable offset in days (default: 107) to fine-tune the temporal shift.
Automatic labels and on-chart visualization.
Compatible with multiple timeframes and logarithmic scales.
Interpretation:
Positive correlation suggests synchronized trends between both assets.
Negative correlation signals divergence or rotation of liquidity.
The time-offset parameter helps estimate when a shift in Gold could later reflect in Bitcoin.
Recommended use:
For macro-financial and global liquidity cycle analysis.
As a complementary tool in cross-asset momentum strategies.
© 2025 – Developed by KManus88 | Inspired by monetary correlation studies and global liquidity cycles.
This script is for educational purposes only and does not constitute financial advice.
FluxGate Daily Swing StrategySummary in one paragraph
FluxGate treats long and short as different ecosystems. It runs two independent engines so the long side can be bold when the tape rewards upside persistence while the short side can stay selective when downside is messy. The core reads three directional drivers from price geometry then removes overlap before gating with clean path checks. The complementary risk module anchors stop distance to a higher timeframe ATR so a unit means the same thing on SPY and BTC. It can add take profit breakeven and an ATR trail that only activates after the trade earns it. If a stop is hit the strategy can re enter in the same direction on the next bar with a daily retry cap that you control. Add it to a clean chart. Use defaults to see the intended behavior. For conservative workflows evaluate on bar close.
Scope and intent
• Markets. Large cap equities and liquid ETFs major FX pairs US index futures and liquid crypto pairs
• Timeframes. From one minute to daily
• Default demo in this publication. SPY on one day timeframe
• Purpose. Reduce false starts without missing sustained trends by fusing independent drivers and suppressing activity when the path is noisy
• Limits. This is a strategy. Orders are simulated on standard candles. Non standard chart types are not supported for execution
Originality and usefulness
• Unique fusion. FluxGate extracts three drivers that look at price from different angles. Direction measures slope of a smoothed guide and scales by realized volatility so a point of slope does not mean a different thing on different symbols. Persistence looks at short sign agreement to reward series of closes that keep direction. Curvature measures the second difference of a local fit to wake up during convex pushes. These three are then orthonormalized so a strong reading in one does not double count through another.
• Gates that matter. Efficiency ratio prefers direct paths over treadmills. Entropy turns up versus down frequency into an information read. Light fractal cohesion punishes wrinkly paths. Together they slow the system in chop and allow it to open up when the path is clean.
• Separate long and short engines. Threshold tilts adapt to the skew of score excursions. That lets long engage earlier when upside distribution supports it and keeps short cautious where downside surprise and venue frictions are common.
• Practical risk behavior. Stops are ATR anchored on a higher timeframe so the unit is portable. Take profit is expressed in R so two R means the same concept across symbols. Breakeven and trailing only activate after a chosen R so early noise does not squeeze a good entry. Re entry after stop lets the system try again without you babysitting the chart.
• Testability. Every major window and the aggression controls live in Inputs. There is no hidden magic number.
Method overview in plain language
Base measures
• Return basis. Natural log of close over prior close for stability and easy aggregation through time. Realized volatility is the standard deviation of returns over a moving window.
• Range basis for risk. ATR computed on a higher timeframe anchor such as day week or month. That anchor is steady across venues and avoids chasing chart specific quirks.
Components
• Directional intensity. Use an EMA of typical price as a guide. Take the day to day slope as raw direction. Divide by realized volatility to get a unit free measure. Soft clip to keep outliers from dominating.
• Persistence. Encode whether each bar closed up or down. Measure short sign agreement so a string of higher closes scores better than a jittery sequence. This favors push continuity without guessing tops or bottoms.
• Curvature. Fit a short linear regression and compute the second difference of the fitted series. Strong curvature flags acceleration that slope alone may miss.
• Efficiency gate. Compare net move to path length over a gate window. Values near one indicate direct paths. Values near zero indicate treadmill behavior.
• Entropy gate. Convert up versus down frequency into a probability of direction. High entropy means coin toss. The gate narrows there.
• Fractal cohesion. A light read of path wrinkliness relative to span. Lower cohesion reduces the urge to act.
• Phase assist. Map price inside a recent channel to a small signed bias that grows with confidence. This helps entries lean toward the right half of the channel without becoming a breakout rule.
• Shock control. Compare short volatility to long volatility. When short term volatility spikes the shock gate temporarily damps activity so the system waits for pressure to normalize.
Fusion rule
• Normalize the three drivers after removing overlap
• Blend with weights that adapt to your aggression input
• Multiply by the gates to respect path quality
• Smooth just enough to avoid jitter while keeping timing responsive
• Compute an adaptive mean and deviation of the score and set separate long and short thresholds with a small tilt informed by skew sign
• The result is one long score and one short score that can cross their thresholds at different times for the same tape which is a feature not a bug
Signal rule
• A long suggestion appears when the long score crosses above its long threshold while all gates are active
• A short suggestion appears when the short score crosses below its short threshold while all gates are active
• If any required gate is missing the state is wait
• When a position is open the status is in long or in short until the complementary risk engine exits or your entry mode closes and flips
Inputs with guidance
Setup Long
• Base length Long. Master window for the long engine. Typical range twenty four to eighty. Raising it improves selectivity and reduces trade count. Lowering it reacts faster but can increase noise
• Aggression Long. Zero to one. Higher values make thresholds more permissive and shorten smoothing
Setup Short
• Base length Short. Master window for the short engine. Typical range twenty eight to ninety six
• Aggression Short. Zero to one. Lower values keep shorts conservative which is often useful on upward drifting symbols
Entries and UI
• Entry mode. Both or Long only or Short only
Complementary risk engine
• Enable risk engine. Turns on bracket exits while keeping your signal logic untouched
• ATR anchor timeframe. Day Week or Month. This sets the structural unit of stop distance
• ATR length. Default fourteen
• Stop multiple. Default one point five times the anchor ATR
• Use take profit. On by default
• Take profit in R. Default two R
• Breakeven trigger in R. Default one R
Usage recipes
Intraday trend focus
• Entry mode Both
• ATR anchor Week
• Aggression Long zero point five Aggression Short zero point three
• Stop multiple one point five Take profit two R
• Expect fewer trades that stick to directional pushes and skip treadmill noise
Intraday mean reversion focus
• Session windows optional if you add them in your copy
• ATR anchor Day
• Lower aggression both sides
• Breakeven later and trailing later so the first bounce has room
• This favors fade entries that still convert into trends when the path stays clean
Swing continuation
• Signal timeframe four hours or one day
• Confirm timeframe one day if you choose to include bias
• ATR anchor Week or Month
• Larger base windows and a steady two R target
• This accepts fewer entries and aims for larger holds
Properties visible in this publication
• Initial capital 25.000
• Base currency USD
• Default order size percent of equity value three - 3% of the total capital
• Pyramiding zero
• Commission zero point zero three percent - 0.03% of total capital
• Slippage five ticks
• Process orders on close off
• Recalculate after order is filled off
• Calc on every tick off
• Bar magnifier off
• Any request security calls use lookahead off everywhere
Realism and responsible publication
• No performance promises. Past results never guarantee future outcomes
• Fills and slippage vary by venue and feed
• Strategies run on standard candles only
• Shapes can update while a bar is forming and settle on close
• Keep risk per trade sensible. Around one percent is typical for study. Above five to ten percent is rarely sustainable
Honest limitations and failure modes
• Sudden news and thin liquidity can break assumptions behind entropy and cohesion reads
• Gap heavy symbols often behave better with a True Range basis for risk than a simple range
• Very quiet regimes can reduce score contrast. Consider longer windows or higher thresholds when markets sleep
• Session windows follow the exchange time of the chart if you add them
• If stop and target can both be inside a single bar this strategy prefers stop first to keep accounting conservative
Open source reuse and credits
• No reused open source beyond public domain building blocks such as ATR EMA and linear regression concepts
Legal
Education and research only. Not investment advice. You are responsible for your decisions. Test on history and in simulation with realistic costs
First 15-Min Breakout (9:30-9:45)This is an experiment with the added 50% marker. I am open to make any adjustments that are necessary