Wskaźnik

Strategia

HalfTrend Long/Short Signal Engine [BigBeluga]HalfTrend Long/Short Signal Engine is an institutional-grade trend tracking toolkit built for TradingView. It filters out minor market noise to deliver definitive, non-repainting long and short entry signals based on asset volatility and structural swing pivots.
Instead of displaying standard lag-heavy moving averages, this system uses an adaptive directional engine to lock onto clean trend lines and overlay automatic risk-management matrices directly onto your chart. It calculates real-time win rates and scans multiple assets simultaneously so you can trade with systematic statistical backup.
🔵 MAIN ENGINE & MARKET CALCULATION MECHANICS
1. Pure HalfTrend Price Filter Matrix
Swing Pivot Trackers: The engine scans local high and low data using an adjustable lookback filter ( Amplitude ) to find actual structural swing points rather than temporary price spikes.
Volatility-Adjusted Bands: It establishes dynamic outer channel boundaries using a 100-period Average True Range calculation divided by two ( ATR/2 ). The total channel width automatically scales using your custom risk buffer parameter ( Channel Deviation ).
Regime Flip Architecture: The system locks into a Bullish Regime when price crosses above structural highs, shifting the main tracking baseline to Green. When price slips below structural lows, it forces a Bearish Regime and changes the tracking baseline to Red.
2. Automated Risk Matrix & Multi-Asset Scanner
Algorithmic Trade Execution: The moment a new trend regime initializes, the engine projects a strict trade tracking matrix showcasing an entry line, a clear stop-loss boundary, and three tiered profit targets (TP1, TP2, and TP3).
Live Performance Dashboard: An integrated on-screen table calculates real-time historical metrics, tracking active wins, losses, current target risk-to-reward ratios ($1:3$), and overall system win rate percentages.
Screener Security Matrix: The background engine leverages real-time multi-asset queries to stream concurrent trend statuses for five separate configurable symbols directly into a secondary visual dashboard.
// Automated Trade Risk & Multi-Asset Tracking Snippet
if buySignal
float dist = atr2 * baseRiskMult
activeSL := close - dist
activeTP1 := close + dist
activeTP2 := close + (dist * 2)
activeTP3 := close + (dist * 3)
tradeState := 1
entryPx := close
t1 = request.security(sym1, timeframe.period, trend)
🔵 WHY IT IS USEFUL
Elimination of Market Noise: Standard moving averages constantly whip back and forth during consolidations. The HalfTrend calculation filters out minor intraday fluctuations, only shifting when a definitive structural high or low is broken.
Mathematical Execution Blueprint: It takes the emotion out of trade management. Every signal comes equipped with dynamic, visually mapped stop losses and a $1:3$ risk-reward profit map that fills with real-time gradient paths.
Macro Market Synchronicity: The multi-asset side-panel allows you to keep an eye on major market drivers (like BTC, ETH, Gold, or major FX pairs) simultaneously, ensuring your trades line up with broader institutional market direction.
🔵 HOW TO USE THE SYSTEM
Trading Long Breakouts: When the system transitions from a bearish regime into a bullish regime, a Green LONG label will print beneath the breakout candle. Execute your position at the white entry line, setting your dynamic stop-loss boundary inside the red risk gradient.
Trading Short Breakdowns: Monitor the system for a shift into a bearish regime, indicated by a Red SHORT label appearing above the asset price. Execute short orders relative to the entry line and utilize the upper red gradient zone to map your protective risk ceiling.
Managing Exits and Targets: Take partial profits sequentially as the asset price moves through the Green target lines (TP1, TP2, and TP3). If a sudden trend reversal prints an opposing signal before your final targets are satisfied, the script automatically triggers a reversal exit rule to preserve accumulated gains.
Streamline your trade execution, manage portfolio risk systematically, and screen multiple sectors at once with the HalfTrend Long/Short Signal Engine workspace. Wskaźnik

Triple Barrier Exit with Meta LabelingOverview
Most tools tell you when to enter. This one frames how a trade would be managed — and then keeps an honest record of how that framing actually resolved. It takes a primary entry signal (its own built-in breakout, or any external signal series you point it at), draws a volatility-scaled profit barrier, stop barrier and time barrier around it, watches which is touched first, and feeds every resolved outcome into a live track record. On top sits a meta-label gate: a small online model that learns, from those resolved outcomes, whether to take or skip the next signal.
It is a research and trade-framing study — not a strategy, not a signal service, and not a validated edge.
Why these parts are ONE tool (mashup rationale)
Each layer exists because the one before it leaves a question open:
The triple barrier. A raw entry signal has no definition of success. Profit / stop / time barriers, scaled by current volatility (ATR or an EWMA of returns), turn a signal into a labelled outcome: profit-hit, stop-hit, or timed-out. Widths are regime-asymmetric — the profit barrier widens in trend and tightens in chop — because a fixed frame misprices the same signal in different conditions.
The trend-scanning vertical. A fixed holding time is arbitrary. The time barrier is instead chosen from candidate horizons by the strongest |t-value| of a linear fit — the horizon over which price is actually trending most decisively.
The meta-label gate. Knowing outcomes isn't the same as acting on them. A small online logistic model, trained only on resolved outcomes, scores each new signal and says TAKE or SKIP. It stays disabled until enough trades have resolved, so it never acts on an untrained model.
The honesty layer. Overlapping trades are not independent samples — so wins are recency-decayed and reported with a Wilson 95% lower bound per regime, alongside a reliability table and a Brier score for the meta-gate itself. If the gate isn't calibrated, the panel says so.
Remove any layer and the tool either mislabels the trade, mistimes it, acts on an untested model, or reports a win-rate it hasn't earned.
How it works
A primary signal fires. If the meta-gate passes, the trade is framed: profit = entry ± (PT × regime multiplier × σ), stop = entry ∓ (SL × regime multiplier × σ), and a vertical barrier holdH bars ahead. The frame is drawn as a forward box that recolours green / red / grey on first touch. Same-bar ties resolve stop-first (the conservative assumption). MFE and MAE are tracked live on the open trade. On resolution, the outcome trains the meta-model and updates the per-regime statistics.
How to use it
Read the panel before you trust the frame.
Meta gate — whether the model would take or skip the current signal (stays "warming" until it has enough resolved samples).
Wilson 95% lower — the honest floor of the win-rate in the current regime. If it isn't above 50%, this framing has not demonstrated an edge here.
Meta Brier — below ~0.25 means the gate's probabilities are reasonably calibrated; above it, ignore the gate.
The most useful thing you can do with it: point it at your own entry signal via the external-source input, and see how your signal resolves under a disciplined exit frame. The suggested size is advisory arithmetic (risk ÷ stop distance), not a recommendation. Only one trade is managed at a time — this is a study of the framing, not a portfolio simulator. The dashboard has a Compact layout (default) and a Pro layout (adds the scanned horizon, Brier, reliability tiers, PT/SL/timeout counts, live MFE/MAE and suggested size).
Universal across markets
Entry source, σ source, barrier widths and horizons are all inputs, so it runs on any symbol and timeframe. It needs no volume. Defaults target intraday index futures.
Non-repainting
Entries are taken and outcomes resolved only on confirmed bars, and the meta-model is trained only on resolved outcomes — so no statistic reads its own future and nothing inflates intrabar. The live "next-trade frame" preview is a forward projection at the current bar only, by design.
Originality
The triple barrier, meta-labelling and trend-scanning are published research concepts, credited below. What's assembled here is the specific synthesis: the triple barrier used as a live exit/management frame rather than an offline training pipeline, regime-asymmetric barrier widths, an online meta-gate that trains itself on the chart in front of you, and an honesty panel that reports the Wilson lower bound, the reliability tiers and the gate's own Brier score. Clean-room implementation; no third-party code reused.
Concept credits
Triple-barrier labelling, meta-labelling, trend-scanning, and sample uniqueness / time-decay for non-IID overlapping outcomes — Marcos López de Prado (Advances in Financial Machine Learning). Here the triple barrier is used as an exit/management frame and a labelling substrate, not as a training pipeline.
Wilson score confidence interval — Edwin B. Wilson · Brier score — Glenn W. Brier
Average True Range — J. Welles Wilder · Efficiency Ratio — Perry Kaufman
Inverse-volatility position sizing — standard risk-management practice
Honest limits
Overlapping trades are not independent, which is exactly why wins are decayed and reported with a Wilson lower bound rather than a raw percentage — treat the win-rate as descriptive, not a probability of future results. The meta-model is a small online logistic fit on three features; it can be miscalibrated, which is why its Brier score is shown. All figures are in-sample, with no costs, slippage or spread. Nothing here predicts price.
Disclaimer
Research and educational tool only. Not financial advice, not a recommendation, and no guarantee of results. The position-size output is arithmetic, not advice. Trading carries risk of loss. Test out-of-sample and make your own decisions. The author accepts no liability for any use. Wskaźnik

Strategia

Wskaźnik

ATR Trailing Stop Strategy with EMA Trend FilterMost stop-loss approaches treat risk as a fixed number, a percentage, a dollar amount, a set number of points. The problem with fixed stops is that they ignore the market's actual behavior at any given moment. A 1% stop that makes sense in a low-volatility environment will get hit constantly in a high-volatility one. A wide fixed stop that survives a volatile period is needlessly large when the market quiets down.
ATR-based trailing stops solve this by scaling the stop distance to what the market is actually doing right now. ATR measures average true range, the average distance price moves per bar over a given period, including gaps. When volatility expands, the stop widens to give the trade room to breathe. When volatility contracts, the stop tightens to protect more of the open profit. The stop follows price as it moves in the trade's direction and never moves backward — only trailing further in the profitable direction or holding its level until price reverses through it and the trade closes.
The EMA filter is added for one specific reason: trailing stop systems are naturally reactive rather than predictive, which means without a trend filter they will generate signals in both directions during choppy, range-bound conditions. The 200 EMA acts as a simple regime gate.
Long trades are only considered when price is above the 200 EMA, broadly in an uptrend. Short trades are only considered when price is below it. This doesn't eliminate losing trades, but it meaningfully reduces the number of counter-trend entries that trail stop systems would otherwise generate in oscillating markets.
How the trailing stop works:
On each bar, the strategy calculates a long stop level at close - (ATR × multiplier) and a short stop level at close + (ATR × multiplier). When price is in an uptrend, the long stop ratchets upward with price but never moves down, it holds its highest reached level until price closes below it, at which point the trend flips to bearish and the stop becomes a downward-trailing short stop. The opposite applies in a downtrend. A trend flip from bearish to bullish generates a long entry signal if price is above the 200 EMA. A flip from bullish to bearish generates a short entry signal if price is below the 200 EMA.
Parameters worth adjusting:
The ATR multiplier controls the sensitivity of the trailing stop. A lower multiplier (1.5x or below) produces a tighter stop that flips trend direction more frequently, useful on lower timeframes where you want faster reaction but will generate more signals. A higher multiplier (2.5x or above) produces a wider stop that flips less often, better suited for higher timeframes where you want to stay in a trend longer and can tolerate larger drawdowns on individual trades before exit. The ATR length controls how many bars the average is computed over. Shorter lengths react faster to recent volatility changes; longer lengths smooth out volatility spikes.
The EMA length can be adjusted depending on your timeframe. 200 periods is the standard for daily charts. On a 4-hour chart, 100 to 150 periods covers a similar calendar range. On a 1-hour chart, 50 to 100 periods is reasonable. The goal is for the EMA to represent the dominant trend, not a short-term moving average that whipsaws with every swing.
What this is not:
This strategy does not predict market direction. It reacts to price behavior and exits when price reverses by a defined volatility-adjusted distance. It will produce losing trades, every trailing stop system does, and sequences of losses in choppy conditions are expected behavior, not a flaw. The expectation is that winning trades capture significantly more than they risk because the stop trails and locks in profit, while losing trades are cut at a defined ATR-based distance.
Evaluate this on your own instruments and timeframes with realistic backtest conditions before drawing any conclusions about expected performance.
Shared for educational purposes. This is not investment advice. Always backtest thoroughly and size positions according to your own risk tolerance. Strategia

Crypto Sniper Pro Smart Trend Range Filter Strategy Hariss 369It is a trend-following strategy designed to identify high-probability entries while filtering out sideways market conditions. It combines multi-timeframe trend confirmation with momentum and liquidity concepts to improve trade quality and reduce noise.
Strategy Features
• Multi-timeframe EMA trend confirmation
• Built-in range filter to avoid low-volatility consolidation
• Liquidity sweep detection for potential reversals
• Momentum breakout confirmation
• ATR-based dynamic Stop Loss and Take Profit
• Optional trading session filter
• Clean and lightweight strategy optimized for backtesting
Entry Logic
Long Entry
Price is above both the lower-timeframe EMA and higher-timeframe EMA.
The market is not inside a detected range.
At least one of the following conditions is satisfied:
Liquidity sweep to the downside followed by recovery
Bullish momentum breakout
Bullish continuation candle
Short Entry
Price is below both the lower-timeframe EMA and higher-timeframe EMA.
The market is not inside a detected range.
At least one of the following conditions is satisfied:
Liquidity sweep to the upside followed by rejection
Bearish momentum breakdown
Bearish continuation candle
Risk Management
The strategy uses ATR-based Stop Loss and Take Profit, allowing risk to automatically adjust to changing market volatility.
Best Markets
Cryptocurrency
Forex
Index CFDs
Stocks
Commodities
Recommended Timeframes
5 Minutes
15 Minutes
1 Hour
4 Hours
Notes
This strategy is intended for educational and research purposes. Always validate performance using TradingView's Strategy Tester before applying it in live markets, and adjust inputs to suit the characteristics of the asset and timeframe you trade.
## Disclaimer
This strategy is provided for educational and research purposes only. It does not constitute financial, investment, or trading advice. Past performance does not guarantee future results, and all trading involves substantial risk, including the potential loss of capital.
The strategy has been designed to assist with market analysis and backtesting. Performance may vary depending on the asset, timeframe, market conditions, broker, commissions, slippage, and user-defined settings. Users are encouraged to thoroughly test and optimize the strategy before using it in live trading.
The author makes no guarantees regarding profitability, accuracy, or suitability for any particular purpose. By using this strategy, you acknowledge that all trading decisions are made at your own risk, and the author shall not be held liable for any financial losses or damages arising from its use.
Strategia

Bollinger Squeeze Breakout + VolumeA volatility contraction often precedes a volatility expansion. When Bollinger Bands narrow significantly, it signals that the market has entered a period of low energy, and low energy rarely lasts. This strategy is built around that principle: it waits for a genuine squeeze, then enters only when price breaks out of the bands with volume confirming that the move has real participation behind it, not just noise.
The logic
A squeeze is identified when the Bollinger Band width (the distance between the upper and lower bands relative to price) falls below its own recent average,meaning volatility is unusually compressed compared to the recent past. Once that condition is met, the strategy watches for price to close outside either band. A long entry triggers when price closes above the upper band during a squeeze, confirmed by volume exceeding its 20-period average. A short entry triggers under the mirrored condition on the lower band. Stops and targets are based on ATR, since the appropriate distance for both should scale with the market's actual movement at the time of entry, not a fixed number.
This approach tends to filter out the false breakouts that occur during already-volatile, choppy conditions, since the entry only fires after a genuine period of compression, which is when breakouts have historically had more follow-through.
Notes on use
The squeeze threshold and lookback length are the two inputs worth tuning per instrument, a 50-period lookback works reasonably well on daily and 4-hour charts, but lower timeframes may benefit from a shorter lookback to react faster to genuine volatility shifts. As with any breakout strategy, backtest across both trending and range-bound periods before drawing conclusions, since this approach is built specifically to perform during regime transitions and may underperform in markets that stay range-bound for extended periods without ever truly compressing.
This is shared for educational and discussion purposes. As always, backtest thoroughly on your own instruments and timeframes, and treat this as a starting framework rather than a finished system. Feedback and variations are welcome in the comments. Strategia

McGinley T3 Flow Campaign [NICK789] v.1McGinley T3 Flow Campaign is a trend-following strategy built around an adaptive signal trail and a campaign-style trade management model.
The script is designed to identify confirmed trend-flow transitions, open a long or short campaign, and then display entry, target, and optional stop levels directly on the chart. It is not intended to predict tops or bottoms. Instead, it waits for the selected flow engine to shift direction and then manages the trade as a structured campaign.
━━━━━━━━━━━━━━━━━━━━━━
CORE IDEA
━━━━━━━━━━━━━━━━━━━━━━
The main concept is to combine an adaptive moving-average engine with an ATR-based trailing structure.
The signal engine can use:
• McGinley Dynamic only
• T3 smoothing only
• A blend of McGinley Dynamic and T3
The McGinley Dynamic is used because it adapts to changes in price speed more smoothly than a standard moving average. T3 smoothing is included as an optional alternative for traders who prefer a smoother trend basis. The blended mode averages both curves to create a balanced engine between responsiveness and smoothness.
After the engine basis is calculated, the script builds an ATR signal trail around it. The trail updates using volatility distance and then locks in a directional path. A confirmed transition in this trail creates the long or short signal.
This means the signal is not based on a simple moving-average crossover. The strategy waits for the adaptive trail itself to shift direction.
━━━━━━━━━━━━━━━━━━━━━━
HOW SIGNALS ARE GENERATED
━━━━━━━━━━━━━━━━━━━━━━
A long signal occurs when the ATR signal trail confirms an upward transition.
A short signal occurs when the ATR signal trail confirms a downward transition.
Signals are confirmed on closed bars. This helps avoid reacting to unfinished candle movement.
The script separates main signals from continuation signals:
• Main BUY / SELL labels appear when a new direction starts
• Smaller continuation triangles appear when the same direction refreshes
This keeps the chart cleaner while still showing when the flow continues in the same direction.
━━━━━━━━━━━━━━━━━━━━━━
CAMPAIGN TARGET MODEL
━━━━━━━━━━━━━━━━━━━━━━
Instead of using only fixed ATR targets, this strategy uses a campaign target system.
There are two target modes:
1. Flow Trail Based
Targets are projected from the distance between price and the active ATR signal trail. This makes the target model expand and contract with the current trend structure.
2. ATR Baseline
Targets are projected from a standard ATR baseline for traders who prefer a more traditional volatility target model.
The Flow Trail Based mode is the default because it connects the target spacing directly to the same adaptive trail that produced the signal.
Target levels are displayed as:
• Entry
• TP1
• TP2
• TP3
• Optional SL
Each level includes its price on the chart.
━━━━━━━━━━━━━━━━━━━━━━
TAKE PROFIT EXIT MODES
━━━━━━━━━━━━━━━━━━━━━━
The strategy includes multiple take-profit behaviours:
• TP1 Only
• TP2 Only
• TP3 Only
• Scale Out TP1 / TP2 / TP3
In scale-out mode, the position is reduced across TP1, TP2, and TP3 using the percentage settings.
In single-target modes, the strategy exits the full position at the selected target.
This allows the same signal engine to be tested with different trade management styles.
━━━━━━━━━━━━━━━━━━━━━━
STOP MODE
━━━━━━━━━━━━━━━━━━━━━━
The stop system has three modes:
• Off
• Visual Only
• Visual + Strategy Exit
By default, Stop Mode is set to Visual Only.
This means the SL line is shown as a campaign reference, but it does not close the strategy trade unless the user changes Stop Mode to Visual + Strategy Exit.
This is intentional because some traders use the stop line as a visual invalidation reference while others want the strategy tester to execute the stop automatically.
━━━━━━━━━━━━━━━━━━━━━━
DASHBOARD
━━━━━━━━━━━━━━━━━━━━━━
The dashboard shows:
• Selected engine mode
• Selected target mode
• Current flow state
• Current strategy position
• Win rate
• PNL and drawdown
━━━━━━━━━━━━━━━━━━━━━━
HOW TO USE
━━━━━━━━━━━━━━━━━━━━━━
1. Choose the engine mode
McGinley Only is the default and gives a responsive adaptive trend read. T3 Only is smoother. Blend mode combines both.
2. Adjust ATR Trail Length and ATR Trail Multiplier
These settings control how sensitive the signal trail is. Lower values react faster but may create more signals. Higher values create smoother signals but can be slower.
3. Choose the Target Mode
Flow Trail Based uses the distance from price to the signal trail. ATR Baseline uses a standard ATR distance.
4. Choose the Take Profit Exit Mode
Use TP1, TP2, or TP3 only for full exits, or use Scale Out mode for partial profit-taking.
5. Choose the Stop Mode
Use Visual Only for chart reference. Use Visual + Strategy Exit if you want the strategy tester to close trades at the stop level.
6. Use the Backtest Start setting
The Backtest Start input lets users control the test period without changing the script.
━━━━━━━━━━━━━━━━━━━━━━
WHAT MAKES THIS SCRIPT DIFFERENT
━━━━━━━━━━━━━━━━━━━━━━
This script is not a simple collection of unrelated indicators.
The components are connected in a single workflow:
• The McGinley/T3 engine creates the adaptive trend basis
• The ATR signal trail converts that basis into a directional flow line
• Confirmed trail transitions create campaign entries
• The target system projects trade levels from the active flow structure
• The dashboard summarizes the active engine, target model, trade state, and performance
The main purpose of the script is to turn an adaptive trend transition into a structured trade campaign with visible entry, targets, stop reference, and performance context.
━━━━━━━━━━━━━━━━━━━━━━
IMPORTANT NOTES
━━━━━━━━━━━━━━━━━━━━━━
This is a strategy script for backtesting and study. It is not financial advice.
Past performance does not guarantee future results.
Results will vary by symbol, timeframe, spread, commission, session, and market condition.
The script works best when users test different settings for the market they trade instead of assuming one preset fits every asset.
Because this is a trend-following model, it can perform well during directional moves but may produce weaker results during sideways or choppy conditions.
Strategia

Strategia

EWO,RSI advanced Signals Strategy - Exhaustion Filter## EWO, RSI, MFI - Advanced Exhaustion Filter
## Overview
Strategy - Advanced Exhaustion Filter is a comprehensive momentum and mean-reversion trading strategy designed for Pine Script v6. It combines multi-indicator momentum tracking with structural price filters to protect traders from "falling knives" during market capitulation and distribution phases.
By blending the Elliott Wave Oscillator (EWO), Relative Strength Index (RSI), Money Flow Index (MFI), and volume-weighted confirmations, this strategy ensures you only enter a trade when genuine momentum returns to the market.
------------------------------
## How It Works##
1. Core Momentum Engine
The strategy relies on three distinct layers of confirmation before generating a trade:
* Elliott Wave Oscillator (EWO): Measures the displacement of price to determine the dominant market wave. Entries require the EWO to be ticking upward from below zero.
* Relative Strength Index (RSI): Filters structural momentum. A long entry triggers when RSI crosses above the critical 40 line, proving a shift out of bearish territory.
* Money Flow Index (MFI): Adds volume-weighted momentum to ensure asset accumulation is actually taking place rather than a low-liquidity squeeze.
2. The Exhaustion & Structural Filter (Anti-Falling Knife)
Standard momentum strategies often fail during deep market sell-offs because indicators flash "buy" on minor relief bounces while price continues to plummet. This script solves that problem using two proprietary rules:
* The Breakout/Breakdown Barrier: The script dynamically tracks the highest high and lowest low of the last N bars (lookback_len). Even if indicators say buy, the strategy will wait until price physically breaks above this local structural barrier.
* Capitulation Memory Flag: If the market enters a state of extreme panic (RSI drops below rsi_oversold), the strategy flags an "Exhaustion Zone". In this zone, the strategy prepares for an explosive trend reset, overriding standard barriers once momentum reverses.
3. Volumetric Confirmation
Signals are filtered through a volume moving average (Volume MA). Entries and exits are only permitted if market volume is at least 80% of its recent average, keeping you out of choppy, illiquid trading sessions.
------------------------------
## Strategy Parameters
* EWO Fast / Slow (Default: 5, 34): The short and long-term moving averages used to calculate the Elliott Wave Oscillator waves.
* RSI Length (Default: 14): The lookback window for trend and exhaustion momentum.
* MFI Length (Default: 14): The lookback window for volume-weighted money flow tracking.
* Breakout Lookback Bars (Default: 10): The number of historical bars used to calculate local structural highs and lows to prevent premature entries.
* Exhaustion RSI Level (Default: 30): The extreme oversold threshold that triggers capitulation logic.
------------------------------
## Best Practices & Asset Classes
* Timeframes: Optimised for 15-minute, 1-hour, and 4-hour charts where structural highs and lows carry significant weight.
* Markets: Highly effective on trending assets with periodic high-volatility liquidations, such as Crypto (BTC, ETH), major Forex pairs, and Tech Stocks.
------------------------------
## ⚠️ Disclaimer
Financial Risk Warning: Financial trading involves substantial risk of loss and is not suitable for every investor. The information, strategies, and script provided here are strictly for educational, informational, and research purposes.
No Advice: This script is not financial advice, an investment recommendation, or a solicitation to buy or sell any financial instrument. Past performance as demonstrated by historical backtesting is never a guarantee of future results.
User Responsibility: Markets change rapidly, and default settings may not fit all assets or market conditions. You are fully responsible for your own trading decisions. Always thoroughly backtest, forward-test on a demo account, and apply your own strict risk management protocols before risking real capital.
Strategia

MACD RSI Signal [XWiseTrade]MACD RSI Signal
The classic MACD settings — 12, 26, 9 — were chosen decades ago for daily stock charts, where they roughly meant "half a month, one month, and a week." Almost everyone then copies those exact numbers onto 5-minute, 15-minute and hourly charts, where they no longer correspond to anything meaningful. This indicator rebuilds the MACD/RSI combination for intraday trading, with periods anchored to how the global trading day is actually structured, and with RSI graded in zones rather than a single overbought/oversold line.
Why simple moving averages, not exponential
Most MACD implementations use exponential moving averages, which deliberately weight recent bars more heavily than older ones. That weighting is a built-in assumption — that the latest price matters more. This indicator uses simple moving averages instead: every bar in the window counts equally. The result is a less manipulated, more faithful read of raw price action, with no human assumption about which bars "should" matter more. For intraday decisions, that neutrality lets the price structure speak for itself rather than through a weighting curve.
Why the periods are 12 / 24 / 8
Read on the 1-hour scale these map to real session structure: 12 ≈ the split between the Euro/US half of the day and the rest; 24 ≈ a full intraday higher-timeframe day; 8 ≈ the length of a single major session (London, New York, Asia). The point isn't that these numbers are magic — it's that the original 12/26/9 only ever made sense as "days," and on intraday charts that meaning is lost. Anchoring to sessions restores a reason for the numbers. You can apply it to higher or lower timeframes, but the 1-hour scale is its reference point.
How the signal is graded
A signal is not a single MACD cross. It requires momentum to be persisting: the MACD histogram must be positive and expanding for a bull case (negative and expanding for a bear case) — momentum actually accelerating, not a one-bar cross that fades.
RSI then grades that momentum, using zones based on familiar ratios (0.214 / 0.382 / 0.618 / 0.786) instead of plain 30/70 — finer resolution for intraday work:
Pass (solid Bull/Bear) — RSI between 0.382 and 0.618 (38.2–61.8): healthy core, room to run.
Warning (small marker) — RSI outside that core but not extreme: momentum persists, but the move is stretched — lower quality.
Veto (no signal) — RSI beyond 0.786 or below 0.214: too extreme, the signal is rejected rather than shown.
How to use it
Add it to a chart — built for intraday, with the 1-hour scale as the reference. Solid Bull/Bear labels are momentum that passed the RSI grade. Faint bull? / bear? markers are persisting momentum that RSI flagged as stretched — treat with caution. No label means the setup was either too weak or vetoed as overextended. The MACD here is built on simple (unweighted) moving averages rather than the usual exponential ones — every period is given equal weight, a more neutral read — and every zone bound is adjustable.
What makes it different
Standard MACD+RSI scripts copy daily-era settings onto every timeframe and use RSI as a single yes/no filter. This one re-anchors the periods to real session structure for intraday use, defines a signal as persisting, expanding momentum rather than a momentary cross, lets RSI grade and veto that momentum across zones instead of a binary line, and uses unweighted moving averages so no single bar is given outsized influence.
Inputs: MACD fast/slow/signal,RSI length, Fibonacci-style zone bounds, cooldown.
These are descriptive signals for discretionary use, not buy/sell recommendations. Wskaźnik

Wskaźnik

Multi-Strategy Portfolio Optimizer [LuxAlgo]The Multi-Strategy Portfolio Optimizer indicator is a comprehensive quantitative tool that evaluates 9 distinct trading setups across trend-following, momentum, and mean-reversion categories to construct an optimized, equally-weighted portfolio.
🔶 USAGE
This script aims to help users identify which trading methodologies are currently performing best on a specific ticker and timeframe, while simultaneously monitoring how well those strategies diversify each other to create a smoother equity curve.
🔹 Strategy Selection & Evaluation
The optimizer evaluates three unique parameter variations for each of the following 9 strategy types:
Supertrend & EMA Crossovers: Captures sustained directional trends.
MACD & CCI: Focuses on momentum shifts and overextended breakouts.
Donchian Channels: Classic breakout logic based on price extremes.
RSI Trend: Uses RSI levels to confirm momentum direction.
RSI Rev, Bollinger Bands & Stochastic: Targets mean-reversion and overbought/oversold exhaustion.
The tool automatically selects the "Best Setting" for each category by comparing the cumulative performance of all three variations across the available chart history. Only the top-performing variation from each category is included in the final portfolio calculation.
🔹 Equity Dashboards
The indicator features two primary visual interfaces to monitor performance and risk:
Floating Curves Box: Displays a real-time equity curve of the total portfolio (thick white line) against the individual active strategies (faded colored lines). This allows users to see the recent performance stability over a user-defined lookback.
Correlation Heatmap: Analyzes the statistical relationship between active strategies. This table uses color-coding to show how similar or different strategy returns are, providing a "Diversification Grade" (e.g., Excellent, Good, Poor) to help users avoid over-exposure to a single market regime.
🔹 Trade Visualization
Users can enable "Show Past & Open Trades" to audit the simulated performance directly on the price action. The script plots entry lines and shaded ATR-based Stop Loss (red) and Take Profit (green) zones for both currently active and historical trades.
🔶 DETAILS
🔹 Best Setting Logic
For every strategy category, the script runs three parallel simulations with different sensitivity settings. The "Best Setting" displayed in the dashboard is the variation that has achieved the highest cumulative percentage return since the beginning of the chart.
🔹 Portfolio Calculation (Equal Weight)
The Portfolio Equity Curve is calculated by averaging the cumulative returns of all active "best" setups on a bar-by-bar basis. This simulates an equally weighted allocation where the capital is distributed evenly across all chosen trading methodologies, aiming to reduce the drawdown typically associated with a single-strategy approach.
🔹 Diversification & Correlation
The Heatmap calculates a Pearson correlation coefficient over a rolling 100-bar window for every pair of active strategies.
Correlation > 0.7 (Red): Strategies are moving in lockstep, offering little diversification.
Correlation near 0 (Yellow): Strategies are independent, providing healthy diversification.
Correlation < -0.2 (Green): Strategies are inversely correlated, which can significantly hedge portfolio volatility.
🔹 Auto-Scaling Polylines
The floating curves dashboard uses a dynamic normalization algorithm. It captures the highest and lowest equity values within the user-defined lookback (Curves Length) and scales them to fit within the box height. This ensures the curves remain visible and proportional regardless of whether the returns are 1% or 100%.
🔶 SETTINGS
🔹 Strategies
Enable : Toggles whether a specific strategy category is evaluated and included in the portfolio math.
🔹 Risk Management
Enable Stop Loss & Take Profit: Toggles the ATR-based exit engine.
ATR Length: The period used for calculating volatility-based exits.
Stop Loss / Take Profit Mult: The multipliers that define the distance of exit targets from the entry price.
Show Past & Open Trades: Visualizes the execution zones on the chart.
🔹 Dashboard
Main Dashboard / Correlation Heatmap: Toggles the visibility of the tables.
Position: Moves the UI elements to different corners of the chart.
Curves Length: Determines the lookback for the floating equity chart.
Curves Vertical Position: Allows you to pin the curves box to the Top, Middle, or Bottom of the price range.
Curves Box Height (%): Adjusts the vertical scale of the equity chart relative to the price action.
Size: Controls the scale of the text and tables (Tiny to Huge). Wskaźnik

FVG Retest Entry Engine [trade_w_samet]🎯 FVG Retest Entry Engine
FVG Retest Entry Engine is a structured Fair Value Gap retest analysis indicator designed to help traders study confirmed gap reactions, structure alignment, filtered entry conditions, and multi-target visual trade models directly on the price chart.
This script focuses on one main concept:
FVG retest-based entry visualization.
It is not designed to be a simple buy/sell signal generator.
It is not designed to show every possible Fair Value Gap.
It is not designed to create constant chart noise.
Instead, the goal of FVG Retest Entry Engine is to detect confirmed structure events, identify eligible Fair Value Gaps, monitor their retests, apply configurable quality checkpoints, and visualize accepted setups using one entry level, one protective stop, and three take-profit levels.
The indicator includes:
• Bullish and bearish market-structure detection
• BOS and CHoCH classification
• Three-candle Fair Value Gap detection
• Internal FVG memory and invalidation handling
• Structure-linked FVG candidate selection
• FVG quality scoring and setup grading
• Armed-zone retest monitoring
• Multiple retest confirmation models
• Volume, Directional Force, and confirmed HTF bias filters
• FVG Retest Passport
• Blocker Lens state reporting
• Confirmed-close signal commitment
• Optional Live Preview dashboard state
• Gap-protected and ATR-based stop-loss models
• TP1, TP2, and TP3 risk-multiple projections
• Optional breakeven movement after TP1
• Active and historical TP / SL areas
• Executed FVG retest zones
• One-active-trade-at-a-time logic
• Mobile chart layout
• Multiple visual themes
• Advanced entry and lifecycle alerts
• JSON webhook support
• Compact bottom-right dashboard
The purpose of this script is to help users visually study where a structure event and an eligible Fair Value Gap combine with a confirmed retest condition.
It should be treated as a chart-analysis and educational decision-support tool.
It is not financial advice.
It is not an automated trading system.
It does not guarantee profitable trades.
It does not execute broker orders.
It does not replace personal analysis, risk management, or trade validation.
━━━━━━━━━━━━━━━━━━━━━━
📌 OVERVIEW
━━━━━━━━━━━━━━━━━━━━━━
At a high level, FVG Retest Entry Engine does the following:
• Detects confirmed bullish and bearish structure breaks.
• Classifies structure events as BOS or CHoCH.
• Detects bullish and bearish three-candle Fair Value Gaps.
• Stores valid FVG zones in internal memory.
• Tracks zone direction, boundaries, age, displacement, volume context, and prior interactions.
• Searches for an eligible FVG after a matching structure event.
• Scores and ranks available FVG candidates.
• Arms the best available zone for retest monitoring.
• Waits for the selected minimum retest delay.
• Detects the selected FVG retest pattern.
• Evaluates reaction quality and optional confluence filters.
• Assigns a setup grade such as A+, A, B, or FILTERED.
• Confirms final entry conditions only when the chart candle closes.
• Draws one Entry, one SL, and three TP levels.
• Tracks TP1, TP2, TP3, stop-loss, and breakeven events.
• Allows only one active trade projection at a time.
• Keeps completed trade areas when historical display is enabled.
• Marks completed models as bullish or bearish FVG Retest outcomes.
• Displays the current bias, engine state, and active levels in the dashboard.
• Provides entry, armed-zone, target, stop, breakeven, and webhook alert options.
The script is intentionally built as a structured process.
It does not include machine-learning prediction.
It does not include guaranteed performance claims.
It does not attempt to forecast every future market movement.
It provides a transparent way to study structure-linked FVG retests and their projected trade lifecycle.
━━━━━━━━━━━━━━━━━━━━━━
🧠 CORE IDEA
━━━━━━━━━━━━━━━━━━━━━━
The core idea behind FVG Retest Entry Engine is based on the relationship between market structure and Fair Value Gap reactions.
A Fair Value Gap represents a three-candle price imbalance.
A bullish FVG is formed when the current candle’s low is above the high from two candles earlier.
A bearish FVG is formed when the current candle’s high is below the low from two candles earlier.
The script does not treat every FVG as an entry.
Instead, it waits for a confirmed structure event and then searches for an eligible FVG that matches that directional context.
The selected FVG becomes an armed zone.
Price must later return to that zone and satisfy the chosen retest condition.
The engine can then evaluate:
• gap size relative to ATR
• formation displacement
• formation volume context
• FVG age
• prior zone interactions
• structure-break quality
• retest depth
• reaction-candle quality
• volume participation
• DI / ADX directional force
• confirmed higher-timeframe bias
• minimum setup grade
The goal is not to show more signals.
The goal is to create a documented and understandable process from structure event to confirmed FVG retest model.
━━━━━━━━━━━━━━━━━━━━━━
🧩 WHY THIS SCRIPT IS NOT A SIMPLE BUY/SELL INDICATOR
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine is not intended to be used as a blind buy/sell system.
The script is structured as a visual review workflow:
Structure event is confirmed
→ matching FVG candidates are reviewed
→ one eligible FVG is selected
→ the FVG becomes armed
→ price returns to the armed zone
→ the retest pattern is checked
→ reaction quality is evaluated
→ enabled filters are checked
→ the setup receives a grade
→ the candle must close with all conditions still valid
→ Entry, SL, TP1, TP2, and TP3 are projected
→ the active model is monitored
→ the model closes at TP3, stop loss, targets complete, or breakeven
→ the completed FVG Retest model is archived visually
Each part has a specific purpose.
The structure system identifies a directional event.
The FVG memory system stores imbalance zones.
The candidate-ranking system selects a relevant gap instead of using every gap.
The armed-zone system separates observation from entry.
The retest logic defines what qualifies as a valid return.
The quality checkpoints reduce setups that fail enabled conditions.
The grading system summarizes internal setup quality.
The entry model provides visual planning levels.
The stop model creates a consistent risk reference.
The three-target model provides staged reward references.
The Blocker Lens explains the current engine state.
The Passport explains why an accepted setup qualified.
The alert system supports monitoring of confirmed events.
This makes the script a structured FVG retest analysis tool, not a guaranteed trade signal generator.
━━━━━━━━━━━━━━━━━━━━━━
⚙️ HOW THE SCRIPT WORKS
━━━━━━━━━━━━━━━━━━━━━━
The script operates through several connected stages.
First, it identifies confirmed swing highs and swing lows.
Price breaking a confirmed swing level can create a bullish or bearish structure event.
The break may be classified as BOS when it continues the current structure bias or CHoCH when it changes that bias.
The engine separately detects three-candle Fair Value Gaps and stores their contextual information.
bool tws_bullish_fvg = bar_index >= 2 and low > high
bool tws_bearish_fvg = bar_index >= 2 and high < low
float tws_bullish_fvg_top = low
float tws_bullish_fvg_bottom = high
float tws_bearish_fvg_top = low
float tws_bearish_fvg_bottom = high
float tws_bullish_fvg_size = tws_bullish_fvg_top - tws_bullish_fvg_bottom
float tws_bearish_fvg_size = tws_bearish_fvg_top - tws_bearish_fvg_bottom
When a structure event occurs, the engine reviews matching FVG candidates within the selected distance and timing limits.
The available candidates are compared using the active profile’s rules.
The selected zone becomes armed and remains under observation until:
• a confirmed retest creates an entry
• the setup expires
• the FVG is invalidated
• another structure search replaces it
Once price interacts with the armed zone, the selected retest model and reaction-quality conditions are checked.
Volume, DI / ADX, and higher-timeframe bias can also be required.
Only a setup that passes the active rules and remains valid at candle close can create a permanent entry model.
━━━━━━━━━━━━━━━━━━━━━━
🔵 BULLISH FVG RETEST LOGIC
━━━━━━━━━━━━━━━━━━━━━━
A bullish FVG Retest setup begins with bullish structure context.
The script requires a confirmed bullish BOS or CHoCH event and then searches for a directionally matching FVG candidate.
The selected zone must remain valid while the engine waits for price to return.
Depending on the chosen profile and retest model, bullish confirmation may require:
• wick contact with the zone
• real-body contact
• a close inside the zone
• a bullish reaction reclaim
• directional recovery above the zone midpoint
• a close above the relevant FVG edge
• a bullish rejection wick
The engine may then check:
• reaction strength
• volume participation
• positive DI dominance
• minimum ADX strength
• confirmed bullish HTF alignment
• minimum accepted grade
When every enabled condition remains valid at candle close, the script creates:
• a bullish FVG RETEST label
• an executed FVG retest box
• an entry reference at the confirmation close
• a protective stop below the setup reference
• TP1, TP2, and TP3 above entry
• blue reward visualization
• red risk visualization
This does not mean price must continue upward.
It means the script detected a bullish FVG retest condition that satisfied the selected rules at the time of confirmation.
━━━━━━━━━━━━━━━━━━━━━━
🔴 BEARISH FVG RETEST LOGIC
━━━━━━━━━━━━━━━━━━━━━━
A bearish FVG Retest setup begins with bearish structure context.
The script requires a confirmed bearish BOS or CHoCH event and then searches for a directionally matching FVG candidate.
The selected zone must remain valid while the engine waits for price to return.
Depending on the chosen profile and retest model, bearish confirmation may require:
• wick contact with the zone
• real-body contact
• a close inside the zone
• a bearish reaction reclaim
• directional recovery below the zone midpoint
• a close below the relevant FVG edge
• a bearish rejection wick
The engine may then check:
• reaction strength
• volume participation
• negative DI dominance
• minimum ADX strength
• confirmed bearish HTF alignment
• minimum accepted grade
When every enabled condition remains valid at candle close, the script creates:
• a bearish FVG RETEST label
• an executed FVG retest box
• an entry reference at the confirmation close
• a protective stop above the setup reference
• TP1, TP2, and TP3 below entry
• blue reward visualization
• red risk visualization
This does not mean price must continue downward.
It means the script detected a bearish FVG retest condition that satisfied the selected rules at the time of confirmation.
━━━━━━━━━━━━━━━━━━━━━━
💎 FVG QUALITY FILTER SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
The script includes a multi-layer FVG quality system to reduce unnecessary chart signals.
This is important because not every gap has the same context and not every retest should create an entry model.
The quality system may evaluate:
• minimum gap size relative to ATR
• displacement of the formation candle
• gap location inside the recent dealing range
• formation-volume context
• gap age
• previous interactions with the zone
• distance from the matching structure event
• structure-break strength
• reaction-candle strength
• volume participation on retest
• DI / ADX directional force
• confirmed HTF bias
• final setup grade
The exact behavior depends on the selected Engine Style.
Original Sync uses the first validated calibration and star-based acceptance logic.
Balanced Flow uses moderate filtering.
Precision Flow applies stricter FVG and retest requirements.
Fast Flow accepts more active conditions.
Position Flow uses wider structural and timing windows.
Custom Lab exposes the advanced thresholds for manual configuration.
The filter system does not guarantee better future outcomes.
It controls how selective the engine is before creating a confirmed visual model.
━━━━━━━━━━━━━━━━━━━━━━
📏 GAP / ATR FILTER
━━━━━━━━━━━━━━━━━━━━━━
The gap-width filter measures the detected FVG against ATR.
This helps the engine reject extremely small imbalance zones relative to current market volatility.
A higher minimum gap-width value makes FVG storage and candidate selection more selective.
A lower value allows smaller gaps to enter the internal memory.
The filter is volatility-adjusted because the same absolute price distance can have different meaning across symbols and timeframes.
The active threshold depends on the chosen profile or Custom Lab value.
A larger gap is not automatically a better setup.
Gap size is only one component of the complete selection and retest process.
━━━━━━━━━━━━━━━━━━━━━━
🕯️ DISPLACEMENT QUALITY FILTER
━━━━━━━━━━━━━━━━━━━━━━
The displacement filter evaluates the directional body of the candle associated with FVG formation.
The formation body is compared with ATR and converted into a bounded internal score.
This helps the script distinguish a stronger directional imbalance from a gap created during weak or narrow price action.
When the Gap Impulse Check is enabled, an FVG must satisfy the selected displacement threshold before it is stored as a valid candidate.
A higher threshold reduces the number of eligible FVGs.
A lower threshold accepts more moderate formations.
The displacement score is an internal quality measurement.
It does not predict whether the zone will hold in the future.
━━━━━━━━━━━━━━━━━━━━━━
📊 REACTION STRENGTH FILTER
━━━━━━━━━━━━━━━━━━━━━━
The reaction-strength filter evaluates the candle that interacts with the armed FVG.
The score can include:
• close location inside the candle
• directional wick quality
• body size relative to ATR
• bullish or bearish candle direction
• penetration depth inside the FVG
The purpose is to separate a basic touch from a more structured directional response.
A higher minimum reaction-strength value requires a clearer response from the zone.
A lower value accepts more retest conditions.
Original Sync can use its original reaction logic without the same adaptive score requirement.
The reaction score is not a win probability.
It is a standardized way to evaluate whether the retest candle matches the selected profile’s quality requirements.
━━━━━━━━━━━━━━━━━━━━━━
🧼 CONFIRMED RETEST FILTER
━━━━━━━━━━━━━━━━━━━━━━
The confirmed-retest layer requires price to satisfy the active retest model and remain valid at candle close.
Available Original Sync reaction patterns include:
• Any Wick Contact
• Real Body Contact
• Close Within Gap
• Reaction Reclaim
Available adaptive reaction models include:
• First Contact
• Directional Recovery
• Edge Reclaim
• Rejection Wick
First Contact accepts basic interaction with the zone.
Directional Recovery requires directional behavior after the interaction.
Edge Reclaim requires price to close through the relevant boundary.
Rejection Wick applies a stricter wick-and-close response.
The script can also use an interaction margin to tolerate minor boundary differences.
A minimum delay prevents the engine from confirming a retest too soon after the structure event.
An expiry window prevents stale armed zones from producing entries too far from their original context.
Final entry commitment remains bar-close based.
━━━━━━━━━━━━━━━━━━━━━━
🎯 ENTRY MODEL
━━━━━━━━━━━━━━━━━━━━━━
When an armed FVG retest passes all enabled conditions, the script creates a visual entry model.
The entry reference is the close of the candle that confirms the retest.
Permanent entries, labels, boxes, and entry alerts are committed only after candle close.
tws_preview_ready := tws_eval_zone_touched and tws_eval_reaction_pass and tws_direction_filters_pass and tws_eval_grade_pass
bool tws_confirmed_entry = tws_preview_ready and barstate.isconfirmed
if tws_confirmed_entry
tws_long_signal := tws_armed_direction == 1
tws_short_signal := tws_armed_direction == -1
tws_entry_event := true
tws_trade_active := true
tws_trade_direction := tws_armed_direction
tws_trade_open_bar := bar_index
tws_trade_entry := close
Confirmed Close mode waits for the candle to finish before the dashboard treats the setup as an entry.
Live Preview can show that current conditions are ready while the realtime candle is still open.
The preview may change intrabar because the candle is unfinished.
It does not create a permanent historical entry model unless the setup remains valid when the candle closes.
The entry is a visual analysis reference.
It is not a broker order and does not require the user to enter a trade.
━━━━━━━━━━━━━━━━━━━━━━
🛑 ATR STOP-LOSS MODEL
━━━━━━━━━━━━━━━━━━━━━━
The script includes two stop-placement models.
Gap-Protected Stop uses the selected FVG boundary plus an ATR-based protective buffer.
For bullish setups, the stop is projected below the FVG.
For bearish setups, the stop is projected above the FVG.
Volatility Stop projects the stop at an ATR multiple from entry.
A minimum stop-distance percentage can prevent extremely narrow visual stops.
float tws_raw_stop =
tws_stop_mode == "Gap-Protected Stop" ?
(
tws_trade_direction == 1 ?
tws_armed_bottom - tws_atr * tws_fvg_stop_buffer_atr :
tws_armed_top + tws_atr * tws_fvg_stop_buffer_atr
) :
(
tws_trade_direction == 1 ?
tws_trade_entry - tws_atr * tws_atr_stop_multiplier :
tws_trade_entry + tws_atr * tws_atr_stop_multiplier
)
float tws_raw_stop_distance = math.abs(tws_trade_entry - tws_raw_stop)
float tws_guaranteed_distance = tws_trade_entry * tws_minimum_stop_percent / 100.0
float tws_final_stop_distance = math.max(tws_raw_stop_distance, tws_guaranteed_distance)
ATR is used because volatility changes across markets and timeframes.
A wider stop changes the projected risk distance and therefore also changes all three target levels.
The displayed SL is a visual planning level only.
It does not place or manage a real broker stop order.
━━━━━━━━━━━━━━━━━━━━━━
🎯 TAKE-PROFIT RR MODEL
━━━━━━━━━━━━━━━━━━━━━━
The script uses three take-profit levels.
Each target is calculated from the distance between entry and the original stop.
float tws_trade_risk = math.abs(tws_trade_entry - tws_trade_original_stop)
tws_trade_tp1 := tws_trade_direction == 1 ? tws_trade_entry + tws_trade_risk * tws_tp1_r : tws_trade_entry - tws_trade_risk * tws_tp1_r
tws_trade_tp2 := tws_trade_direction == 1 ? tws_trade_entry + tws_trade_risk * tws_tp2_r : tws_trade_entry - tws_trade_risk * tws_tp2_r
tws_trade_tp3 := tws_trade_direction == 1 ? tws_trade_entry + tws_trade_risk * tws_tp3_r : tws_trade_entry - tws_trade_risk * tws_tp3_r
The default concept is:
TP1 = first risk-multiple target
TP2 = second risk-multiple target
TP3 = final risk-multiple target
The exact R values can be adjusted in Position Architecture.
The script also contains visual position-share percentages for TP1, TP2, and TP3.
These shares are used by the internal lifecycle model.
They do not represent a broker account, real position size, or verified financial performance.
The RR settings only control projected visual distances.
They should not be interpreted as recommendations or guaranteed objectives.
━━━━━━━━━━━━━━━━━━━━━━
📦 ACTIVE TP / SL BOX SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
When a confirmed FVG Retest entry appears, the script can draw a complete visual trade model.
The visual model includes:
• executed FVG retest zone
• entry line
• original stop line
• active stop line
• TP1 line
• TP2 line
• TP3 line
• red risk box
• blue reward box
• Entry price label
• SL price label
• TP1, TP2, and TP3 price labels
• bullish or bearish entry label
The active boxes extend to the right while the model is open.
When the model closes, the right edge is fixed at the closing candle.
If Keep Completed Trade Areas is enabled, completed boxes and lines remain visible for historical review.
The Completed Trade History Limit controls how many previous visual models are retained.
The TP area uses a blue-toned visual palette.
TP price labels use a different, darker background so they remain distinct from the reward box.
The SL area remains red for clearer risk separation.
━━━━━━━━━━━━━━━━━━━━━━
🚦 ONE ACTIVE TRADE AT A TIME
━━━━━━━━━━━━━━━━━━━━━━
The script includes one-active-trade-at-a-time logic.
If a trade model is active, the engine does not create another trade model until the current one closes.
The active model may close through:
• TP3
• targets complete
• stop loss
• breakeven exit
This design separates:
• FVG and structure detection
• trade-model creation permission
The engine can continue calculating market context while a model is active, but another entry model is not opened.
This helps prevent overlapping TP / SL areas and keeps the chart easier to interpret.
The one-active-model rule is a visual management decision.
It is not a restriction on the user’s personal trading activity.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ SAME-CANDLE TP / SL HANDLING
━━━━━━━━━━━━━━━━━━━━━━
If a target and the active stop are both touched on the same candle, standard OHLC data cannot reveal the true intrabar sequence.
The script therefore includes two selectable assumptions:
Protective First
Target First
Protective First assumes the stop is processed before target events.
Target First processes available target events before the stop check.
bool tws_conservative_mode =
tws_intrabar_priority == "Protective First"
if tws_conservative_mode and tws_stop_touched
tws_trade_remaining_percent := 0.0
tws_close_trade := true
tws_close_reason := tws_trade_active_stop == tws_trade_entry ? "BREAKEVEN" : "STOP LOSS"
tws_final_exit_price := tws_trade_active_stop
else
if not tws_tp1_reached and tws_tp1_touched
tws_tp1_reached := true
tws_tp1_event := true
Protective First is the more conservative bar-based assumption.
Target First is more optimistic.
Neither option reproduces exact tick-by-tick broker execution.
The model does not include spread, slippage, commissions, latency, or partial-fill behavior.
━━━━━━━━━━━━━━━━━━━━━━
🏷️ FVG RETEST LABELS
━━━━━━━━━━━━━━━━━━━━━━
The script uses clear directional FVG Retest labels.
Bullish entry labels use:
🟢 FVG RETEST
📈 LONG
Bearish entry labels use:
🔴 FVG RETEST
📉 SHORT
Entry labels can also display:
• grade
• setup score
• FVG age
• retest depth
• Passport information
Completed-model labels emphasize that the closed model originated from an FVG retest.
A completed bullish model can display:
🟢 BULLISH FVG RETEST
🔒 MODEL CLOSED
🎯 close reason
⭐ grade
TP1 / TP2 / TP3 status
A completed bearish model uses the corresponding bearish wording and color.
The labels do not display USD profit or account-profit claims.
All chart labels use bold and italic text formatting.
The signal-label size can be adjusted from the settings.
━━━━━━━━━━━━━━━━━━━━━━
📍 FVG ZONE DISPLAY MODES
━━━━━━━━━━━━━━━━━━━━━━
The FVG display system includes three modes:
Hidden
Selected Gap
All Active Gaps
Hidden mode removes active FVG memory boxes from the chart while allowing the engine to continue calculating them internally.
Selected Gap shows only the FVG currently armed for retest monitoring.
All Active Gaps displays every currently stored and valid FVG zone.
Show Executed FVG Retests separately controls whether the FVG zone that created an entry remains highlighted as part of the trade model.
The selected display mode affects visual presentation only.
It does not change the underlying FVG calculations.
For the cleanest chart, Selected Gap is generally the most focused mode.
All Active Gaps can be useful for research but may create more chart density.
━━━━━━━━━━━━━━━━━━━━━━
🧹 FVG INVALIDATION
━━━━━━━━━━━━━━━━━━━━━━
The script can automatically remove invalidated FVG zones.
A bullish FVG may be invalidated when confirmed price action closes through the zone in the opposite direction.
A bearish FVG may be invalidated when confirmed price action closes through its opposite boundary.
An armed zone can also be cleared when:
• its retest window expires
• the zone exceeds the permitted lifetime
• the internal memory limit removes an older gap
• the active structure search is replaced
When an armed FVG becomes invalid, the Blocker Lens can display FVG INVALIDATED.
When the retest window expires, it can display SETUP EXPIRED.
Removing invalidated or stale zones helps prevent outdated FVGs from creating later entries outside their intended context.
Users can disable automatic invalidation removal if they prefer to retain more zones visually.
━━━━━━━━━━━━━━━━━━━━━━
📟 DASHBOARD
━━━━━━━━━━━━━━━━━━━━━━
The script includes a compact dashboard positioned in the bottom-right corner.
The dashboard displays:
• BIAS
• STATE
• ENTRY
• TP1
• TP2
• TP3
• SL
BIAS uses the confirmed higher-timeframe filter when that filter is enabled and valid.
Otherwise, it reflects the current internal structure bias.
STATE is powered by the Blocker Lens.
Possible states include:
• WAITING STRUCTURE
• SCANNING FVG
• NO ELIGIBLE FVG
• FVG ARMED
• RETEST DELAY
• WAITING RETEST
• VOLUME BLOCK
• DI BLOCK
• HTF BLOCK
• WEAK REACTION
• GRADE BLOCK
• LIVE PREVIEW READY
• WAITING BAR CLOSE
• TRADE ACTIVE
• COOLDOWN
• SETUP EXPIRED
• FVG INVALIDATED
The dashboard size can be set to Micro, Compact, or Standard.
The dashboard is designed to summarize engine state and current price references.
It is not a performance report.
It is not a replacement for TradingView Strategy Tester.
━━━━━━━━━━━━━━━━━━━━━━
🚨 ALERT SYSTEM
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine includes advanced alert options for:
• FVG armed
• bullish FVG Retest entry
• bearish FVG Retest entry
• any FVG Retest entry
• TP1 reached
• TP2 reached
• TP3 reached
• breakeven activated
• stop loss
• breakeven exit
Alert packages include:
Off
Qualified Entries
Premium Entries
Full Lifecycle
Webhook JSON
Qualified Entries focuses on confirmed accepted entries.
Premium Entries applies stricter grade-based alert delivery.
Full Lifecycle includes entry and management events.
Webhook JSON sends structured event messages for external processing.
Alert Direction can be limited to Both Directions, Bullish Only, or Bearish Only.
Minimum Alert Grade can be set to All Qualified, A / A+, or A+ Only.
Alert filtering affects alert delivery only.
It does not change the chart’s signal calculations.
alertcondition(tws_armed_alert_event, title="trade_w_samet • FVG ARMED", message='trade_w_samet FVG ARMED | {{ticker}} | TF: {{interval}} | Score: {{plot("SIGNAL_SCORE")}}')
alertcondition(tws_entry_alert_event and tws_trade_direction == 1, title="trade_w_samet • BULLISH FVG RETEST", message='trade_w_samet BULLISH FVG RETEST | {{ticker}} | TF: {{interval}} | Score: {{plot("SIGNAL_SCORE")}} | Entry: {{plot("ENTRY")}} | SL: {{plot("SL")}} | TP1: {{plot("TP1")}} | TP2: {{plot("TP2")}} | TP3: {{plot("TP3")}}')
alertcondition(tws_entry_alert_event and tws_trade_direction == -1, title="trade_w_samet • BEARISH FVG RETEST", message='trade_w_samet BEARISH FVG RETEST | {{ticker}} | TF: {{interval}} | Score: {{plot("SIGNAL_SCORE")}} | Entry: {{plot("ENTRY")}} | SL: {{plot("SL")}} | TP1: {{plot("TP1")}} | TP2: {{plot("TP2")}} | TP3: {{plot("TP3")}}')
alertcondition(tws_tp1_alert_event, title="trade_w_samet • TP1 REACHED", message='trade_w_samet TP1 REACHED | {{ticker}} | TP1: {{plot("TP1")}}')
alertcondition(tws_stop_alert_event, title="trade_w_samet • STOP LOSS", message='trade_w_samet STOP LOSS | {{ticker}} | SL: {{plot("SL")}}')
Alerts are monitoring tools only.
They do not execute trades or place broker orders.
━━━━━━━━━━━━━━━━━━━━━━
🔔 HOW TO USE ALERTS
━━━━━━━━━━━━━━━━━━━━━━
A practical alert workflow:
1. Add FVG Retest Entry Engine to the chart.
2. Select the desired Engine Style and confirmation settings.
3. Open TradingView’s alert window.
4. Select the indicator as the alert condition.
5. Choose the desired entry or lifecycle condition.
6. Select the alert frequency appropriate for confirmed-candle monitoring.
7. Use the Alert Package, direction, and grade controls inside the indicator when needed.
8. Add a webhook URL only when using a compatible external workflow.
9. Test the alert configuration before depending on it.
10. Confirm every event with personal analysis and risk management.
For confirmed entry monitoring, users should avoid treating provisional realtime candle conditions as permanent signals.
Entry alerts are designed around the script’s confirmed event variables.
Alert delivery can still depend on TradingView servers, the user’s alert configuration, data availability, and any external webhook destination.
━━━━━━━━━━━━━━━━━━━━━━
🧪 HOW TO USE THE INDICATOR
━━━━━━━━━━━━━━━━━━━━━━
A practical workflow:
1. Add FVG Retest Entry Engine to a standard candlestick chart.
2. Begin with Original Sync or Balanced Flow.
3. Keep Signal Timing on Confirmed Close for the clearest workflow.
4. Use Selected Gap to keep the chart focused.
5. Observe the dashboard STATE value.
6. Wait for a confirmed structure event and an armed FVG.
7. Review the FVG zone before the retest occurs.
8. When price returns, allow the selected retest model and filters to complete.
9. Review the FVG Retest Passport when an entry appears.
10. Use the displayed Entry, SL, TP1, TP2, and TP3 as visual references only.
11. Evaluate whether the setup fits personal structure, liquidity, session, and risk rules.
12. Use alerts for monitoring rather than blind execution.
13. Review completed FVG Retest labels to understand the model lifecycle.
14. Test settings on the exact markets and timeframes personally studied.
The indicator is best used as a structured FVG retest review tool.
It should not be used as an automatic decision-maker.
━━━━━━━━━━━━━━━━━━━━━━
⚙️ SETTINGS REFERENCE
━━━━━━━━━━━━━━━━━━━━━━
⚡ Signal Blueprint
Engine Style
Controls the active configuration profile.
Available profiles:
Original Sync
Balanced Flow
Precision Flow
Fast Flow
Position Flow
Custom Lab
Allow Bullish Setups
Enables or disables bullish FVG Retest models.
Allow Bearish Setups
Enables or disables bearish FVG Retest models.
━━━━━━━━━━━━━━━━━━━━━━
🪪 Retest Experience
FVG Retest Passport
Controls whether Passport information is Off, Compact, or Detailed.
Show Blocker Lens
Shows or hides the engine STATE explanation in the dashboard.
Signal Timing
Selects Confirmed Close or Live Preview behavior.
Live Preview affects the dashboard’s provisional realtime state. Permanent entries remain candle-close confirmed.
━━━━━━━━━━━━━━━━━━━━━━
🧬 Original Sync Engine
Original Signal Calibration
Selects Manual Sync, Bitcoin Map, Ethereum Map, Solana Map, or Gold Map.
Structure Window
Controls pivot sensitivity in Manual Sync.
Minimum Gap Footprint — ATR
Controls the minimum FVG width.
Gap Lifetime
Controls how long stored FVGs remain eligible.
Gap Memory Capacity
Controls the number of stored zones.
Break-to-Gap Distance
Controls the maximum allowed distance between structure context and FVG eligibility.
After-Break Scan Window
Controls how long the engine continues searching after a break.
Reaction Pattern
Selects Any Wick Contact, Real Body Contact, Close Within Gap, or Reaction Reclaim.
Reaction Margin %
Adds tolerance around FVG boundaries.
Minimum Reaction Delay
Controls how many bars must pass before retest confirmation.
Reaction Expiry Bars
Controls how long the armed setup may wait.
Participation Multiplier
Controls the Original Sync volume requirement.
Minimum Directional Force
Controls the Original Sync ADX threshold.
Minimum Sync Rating
Controls the minimum accepted star rating.
Minimum Risk Distance %
Prevents extremely narrow stops.
━━━━━━━━━━━━━━━━━━━━━━
🧭 Structure Pulse
Structure Sensitivity
Controls pivot detection in Custom Lab.
Display Structure Tags
Shows or hides BOS / CHoCH labels.
Close-Lock Breaks
Requires a candle close beyond structure when enabled.
Break Momentum Check
Requires directional expansion on the break candle.
Break Body Threshold — ATR
Controls the required break-candle body size.
Break Clearance — ATR
Adds an ATR-based buffer beyond the structure level.
━━━━━━━━━━━━━━━━━━━━━━
🧱 Gap Intelligence
Minimum Gap Width — ATR
Controls the minimum stored FVG size.
Gap Impulse Check
Enables displacement filtering.
Minimum Gap Impulse
Controls the required formation displacement.
Minimum Gap Score
Controls the minimum candidate-quality score.
Allowed Prior Reactions
Controls how many previous zone interactions are accepted.
Gap Expiry Bars
Controls maximum FVG age.
Active Gap Capacity
Controls stored-zone capacity.
Maximum Structure Link
Controls the maximum structure-to-FVG distance.
Break Follow-Through Window
Controls post-break candidate scanning.
Delete Invalidated Gaps
Removes zones invalidated by confirmed opposite price action.
━━━━━━━━━━━━━━━━━━━━━━
🎯 Reaction Trigger
Reaction Model
Selects First Contact, Directional Recovery, Edge Reclaim, or Rejection Wick.
Gap Interaction Margin %
Adds tolerance around FVG boundaries.
Minimum Reaction Strength
Controls the required retest-candle score.
Reaction Delay Bars
Controls the minimum delay before retest confirmation.
Setup Expiry Bars
Controls how long the armed zone remains available.
Signal Cooldown Bars
Controls the delay after a completed model before another entry is permitted.
━━━━━━━━━━━━━━━━━━━━━━
🛂 Quality Checkpoints
Volume Participation Check
Enables or disables the retest-volume filter.
Volume Baseline Length
Controls the volume moving-average period.
Required Volume Expansion
Controls the required volume multiplier.
Directional Force Check
Enables or disables DI / ADX filtering.
Directional Force Length
Controls the DI period.
Trend Strength Smoothing
Controls ADX smoothing.
Minimum Trend Strength
Controls the required ADX value.
Higher-Timeframe Bias Check
Enables or disables HTF directional alignment.
Bias Timeframe
Selects the higher timeframe.
Bias Fast EMA
Controls the fast HTF EMA length.
Bias Slow EMA
Controls the slow HTF EMA length.
Minimum Setup Grade
Selects B Grade or Better, A Grade or Better, or A+ Only.
The HTF layer uses previous completed higher-timeframe values.
float tws_htf_close = request.security(
syminfo.tickerid,
tws_htf_timeframe,
close ,
barmerge.gaps_off,
barmerge.lookahead_on
)
float tws_htf_fast_ema = request.security(
syminfo.tickerid,
tws_htf_timeframe,
ta.ema(close, tws_htf_fast_length) ,
barmerge.gaps_off,
barmerge.lookahead_on
)
float tws_htf_slow_ema = request.security(
syminfo.tickerid,
tws_htf_timeframe,
ta.ema(close, tws_htf_slow_length) ,
barmerge.gaps_off,
barmerge.lookahead_on
)
━━━━━━━━━━━━━━━━━━━━━━
🛡️ Position Architecture
ATR Calculation Length
Controls ATR calculation.
Stop Placement Model
Selects Gap-Protected Stop or Volatility Stop.
Volatility Stop Multiplier
Controls ATR stop distance from entry.
Gap Stop Buffer — ATR
Controls the protective distance beyond the FVG.
Minimum Stop Distance %
Prevents extremely narrow risk zones.
TP1 Risk Multiple
Controls the first target distance.
TP2 Risk Multiple
Controls the second target distance.
TP3 Risk Multiple
Controls the final target distance.
TP1 Position Share %
Controls the internal visual share assigned to TP1.
TP2 Position Share %
Controls the internal visual share assigned to TP2.
TP3 Position Share %
Controls the internal visual share assigned to TP3.
Move Stop to Entry After TP1
Moves the active stop to entry after TP1 according to confirmed lifecycle rules.
Same-Candle Priority
Selects Protective First or Target First.
━━━━━━━━━━━━━━━━━━━━━━
🎨 Chart Design
Color System
Selects Obsidian Signal, Carbon Grid, Ivory Pulse, Neon Voltage, Acid Circuit, or Violet Flux.
Gap Display Mode
Selects Hidden, Selected Gap, or All Active Gaps.
Show Executed FVG Retests
Shows or hides the FVG zone used by a confirmed trade model.
Display TP / SL Areas
Shows or hides the reward and risk boxes.
Keep Completed Trade Areas
Keeps completed model boxes and lines.
Completed Trade History Limit
Controls the maximum historical visual models.
Active Area Projection
Controls the initial right-side projection length.
Chart Layout
Selects Desktop or Mobile.
Signal Label Size
Selects Micro, Compact, Standard, or Large.
Dashboard Size
Selects Micro, Compact, or Standard.
Display Bias EMA
Shows or hides the confirmed HTF fast EMA reference.
Display Setup Dashboard
Shows or hides the bottom-right dashboard.
━━━━━━━━━━━━━━━━━━━━━━
📡 Alert Center
Alert Package
Selects Off, Qualified Entries, Premium Entries, Full Lifecycle, or Webhook JSON.
Alert Direction
Selects Both Directions, Bullish Only, or Bearish Only.
Minimum Alert Grade
Selects All Qualified, A / A+, or A+ Only.
Alert When FVG Is Armed
Enables armed-zone alerts for compatible packages.
Alert When Stop Moves to Entry
Enables breakeven-activation alerts for compatible packages.
━━━━━━━━━━━━━━━━━━━━━━
🧠 WHAT MAKES THIS SCRIPT ORIGINAL
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine uses familiar analytical concepts such as:
• Fair Value Gaps
• swing-point structure
• BOS and CHoCH
• ATR
• volume analysis
• DI / ADX
• higher-timeframe EMA bias
• risk/reward projection
• staged targets
• breakeven management
These concepts are not unique by themselves.
The originality of this script lies in how they are organized into a transparent FVG retest workflow:
Structure confirmation
→ directional FVG memory
→ contextual candidate comparison
→ selected armed zone
→ configurable retest validation
→ reaction-quality evaluation
→ optional volume, DI, and HTF checkpoints
→ setup grading
→ confirmed-close entry commitment
→ three-target visual management
→ optional breakeven movement
→ completed FVG Retest archiving
→ Blocker Lens state reporting
→ Passport explanation
→ lifecycle alerts
Distinctive implementation features include:
• structure-linked FVG selection instead of signaling every gap
• multiple Engine Style profiles
• Original Sync market calibrations
• an armed-zone state before entry
• candidate ranking using several FVG characteristics
• multiple retest models
• a visible reason when an entry is waiting or blocked
• a Passport explaining accepted setup context
• confirmed-close permanent signal commitment
• previous-completed HTF values
• executed FVG zone preservation
• three-stage target management
• Desktop and Mobile display modes
• alert filtering separated from chart calculations
This structure is designed to provide a focused and explainable review process without relying on hidden prediction claims.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ IMPORTANT PRACTICAL NOTES
━━━━━━━━━━━━━━━━━━━━━━
The script’s behavior depends heavily on settings and market conditions.
Signal frequency and visual output may change based on:
• Engine Style
• structure sensitivity
• close-based or wick-based breaks
• break momentum requirements
• minimum FVG width
• displacement filtering
• candidate-score threshold
• previous zone interactions
• FVG lifetime
• retest model
• reaction-strength threshold
• retest delay
• setup expiry
• volume filter settings
• DI / ADX settings
• HTF timeframe and EMA lengths
• minimum setup grade
• stop model
• target multiples
• signal cooldown
• timeframe
• symbol volatility
• market session
• available historical bars
A setting that appears clean on one market may behave differently on another.
A profile that produces suitable frequency on one timeframe may be too strict or too active on another.
Volume behavior can differ across asset classes and data providers.
Higher-timeframe filtering only operates as intended when the selected bias timeframe is genuinely higher than the chart timeframe.
Users should test the exact symbol, timeframe, profile, and session they personally study.
━━━━━━━━━━━━━━━━━━━━━━
⚠️ LIMITATIONS AND SHORTCOMINGS
━━━━━━━━━━━━━━━━━━━━━━
This script has important limitations:
It does not guarantee profitable trades.
It does not predict future price movement.
It does not replace risk management.
It does not execute trades.
It does not place broker orders.
It does not include broker slippage.
It does not include commissions.
It does not include spreads.
It does not include execution delay.
It does not include partial-fill behavior.
It uses bar-based chart data.
Same-candle TP / SL order cannot be known from standard OHLC data.
Same-Candle Priority is a modeling assumption.
Live Preview can change intrabar because the realtime candle is unfinished.
Permanent entry models are committed only after bar close.
Confirmed pivots require future bars before becoming available as confirmed swing points.
The dashboard is not TradingView Strategy Tester.
The internal target-share model is not account-performance reporting.
Historical boxes and completed labels do not guarantee similar future behavior.
Setup grades are internal classifications, not win probabilities.
Filter settings do not guarantee improved future results.
Higher-timeframe values depend on selected timeframe and available data.
Data-feed revisions or chart-history differences can affect historical calculations.
Alert delivery depends on TradingView and the user’s alert configuration.
Webhook delivery also depends on the external destination.
One-active-trade logic is a visual management rule, not broker execution logic.
For these reasons, FVG Retest Entry Engine should be used as an educational decision-support and chart-analysis tool, not as a standalone automated trading strategy.
━━━━━━━━━━━━━━━━━━━━━━
👤 WHO THIS SCRIPT MAY BE USEFUL FOR
━━━━━━━━━━━━━━━━━━━━━━
This script may be useful for traders who:
• study Fair Value Gap retests
• use BOS and CHoCH context
• prefer selected FVGs instead of every raw gap
• want a visible armed-zone workflow
• want to understand why a setup is waiting or blocked
• prefer confirmed-close entries
• want a setup-grade framework
• want Entry, SL, TP1, TP2, and TP3 visualization
• want optional breakeven behavior
• want completed FVG Retest models preserved visually
• use higher-timeframe directional context
• want mobile-friendly chart presentation
• use lifecycle alerts for monitoring
• want a structured educational analysis framework
It may be less suitable for users who:
• want guaranteed buy/sell signals
• want a fully automated trading bot
• want every raw FVG to create an entry
• expect one profile to work on every market
• expect grades to represent guaranteed probability
• require exact tick-level execution simulation
• expect visual projections to match broker fills
• expect alerts to execute trades automatically
• want an indicator to replace independent decision-making
━━━━━━━━━━━━━━━━━━━━━━
🧭 BEST PRACTICE SUGGESTIONS
━━━━━━━━━━━━━━━━━━━━━━
For cleaner review:
• Start with Original Sync or Balanced Flow.
• Keep Signal Timing on Confirmed Close.
• Use Selected Gap to reduce chart clutter.
• Enable Blocker Lens while learning the engine workflow.
• Use Compact Passport for concise context.
• Use Detailed Passport when reviewing why a setup qualified.
• Review the armed FVG before the entry appears.
• Check whether the FVG retest agrees with personal market-structure analysis.
• Evaluate the displayed stop against nearby structure and volatility.
• Treat TP1, TP2, and TP3 as planning references only.
• Keep Protective First when a conservative same-candle assumption is preferred.
• Use Precision Flow when fewer, stricter setups are preferred.
• Use Fast Flow only after understanding its higher signal frequency.
• Use Custom Lab only after learning how each threshold affects the engine.
• Use Mobile layout on smaller screens.
• Use alerts for monitoring, not blind execution.
• Always apply independent analysis, risk management, and position sizing.
━━━━━━━━━━━━━━━━━━━━━━
🔓 PUBLICATION NOTE
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine is published as an educational and visual market-analysis tool.
The purpose of this description is to explain:
• what the script does
• how structure events are confirmed
• how three-candle FVGs are detected
• how FVGs are stored and invalidated
• how structure and FVG candidates are linked
• how an FVG becomes armed
• how retest models work
• how reaction quality is evaluated
• how volume, DI / ADX, and HTF checkpoints operate
• how setup grades are assigned
• how Confirmed Close and Live Preview differ
• how Entry and stop levels are calculated
• how TP1, TP2, and TP3 are projected
• how breakeven and same-candle assumptions work
• how active and completed trade areas behave
• what the Passport and Blocker Lens show
• what the dashboard displays
• what the alert packages do
• what the limitations are
• how the indicator should and should not be used
The script is designed to support structured analysis.
It does not promise profitable results.
It does not remove market risk.
It does not execute trades.
It should not be used as a blind buy/sell system.
It is best used as a visual framework for reviewing structure-linked FVG retests and projected risk/reward behavior.
━━━━━━━━━━━━━━━━━━━━━━
🛡️ DISCLAIMER
━━━━━━━━━━━━━━━━━━━━━━
FVG Retest Entry Engine is provided for educational and informational purposes only.
It does not constitute financial, investment, trading, legal, or tax advice.
No indicator can guarantee future results.
Markets are uncertain, conditions change, and historical behavior does not ensure future performance.
Every user is responsible for their own analysis, validation, risk management, position sizing, alert configuration, trading decisions, and broker execution.
The structure labels, FVG zones, armed-zone states, Passport values, Blocker Lens messages, grades, scores, entry references, stop-loss levels, take-profit levels, TP / SL boxes, dashboard values, completed-model labels, and alerts are visual analysis tools only.
Use this script as a structured decision-support and visual review framework, not as a promise of profitability or a substitute for independent judgment.
Wskaźnik

Strategy Forecast EngineThe Strategy Forecast Engine is a regime-based Monte Carlo forecasting tool that estimates the future return distribution of trend-following strategies across different market environments. The model identifies the current market regime, conditions forecasts on historical returns observed during comparable regimes, and generates thousands of potential future price paths using Monte Carlo simulation. The resulting return distribution is presented through percentile projections and a structured, color-coded table that provides a comprehensive assessment of the forecast.
First, the model identifies the current market regime using the selected trend-following strategy. Users can choose between a moving-average crossover strategy, a volatility-based trailing stop strategy, or a combined strategy that incorporates both approaches. Supported moving-average types include the Exponential Moving Average (EMA), Simple Moving Average (SMA), Wilder’s Moving Average (RMA), and Weighted Moving Average (WMA). Supported volatility types include the Average True Range (ATR), Standard Deviation (SD), and Mean Absolute Deviation (MAD). By default, the model applies an asymmetric design in which conflicting signals default to bullish unless neutral regimes are enabled in the menu. Market regimes are determined as follows:
Bullish Trend Regime = (Fast MA – Slow MA) > (ATR × Trend Margin)
Bearish Trend Regime = (Fast MA – Slow MA) < –(ATR × Trend Margin)
Bullish Volatility Regime = Price > (Highest Price – (Volatility × Stop Factor))
Bearish Volatility Regime = Price < (Lowest Price + (Volatility × Stop Factor))
Bullish Combined Regime = Bullish Trend Regime and Bullish Volatility Regime
Bearish Combined Regime = Bearish Trend Regime and Bearish Volatility Regime
Once the current regime has been identified, the model collects all historical logarithmic returns that occurred during the same regime beginning from the selected start date. Only returns from the matching regime are used to generate the forecast, allowing projections to be conditioned on historically comparable market environments rather than treating all historical observations as equally relevant. If duration-adjusted forecast is enabled in the menu, the model further restricts the sample pool to returns from regimes that were at least as mature as the current regime.
The Monte Carlo simulation engine then generates thousands of possible future price paths over the selected forecast horizon. Each simulation randomly samples historical returns from the sample pool associated with the current regime and compounds them forward to generate a potential future price path. This process is repeated for the specified number of simulations to produce a broad range of possible future outcomes. The random seed controls reproducibility, ensuring that identical settings produce identical forecasts. Once all individual simulations have been completed, the resulting return distribution is summarized using percentile projections:
95% = 5% of simulations ended above this level and 95% ended below it.
75% = 25% of simulations ended above this level and 75% ended below it.
Median = 50% of simulations ended above this level and 50% ended below it.
25% = 25% of simulations ended below this level and 75% ended above it.
5% = 5% of simulations ended below this level and 95% ended above it.
The upper quartile (75%) and lower quartile (25%) define the Interquartile Range (IQR), which contains the middle 50% of all simulated outcomes and represents the central range of the projected outcome distribution. The upper and lower tail percentiles can be set to 10% (90% / 10%), 5% (95% / 5%), or 1% (99% / 1%). The default setting is 5%, which captures the middle 90% of simulated outcomes. At 10%, the range captures 80% of simulated outcomes, while at 1%, the range captures 98% of simulated outcomes. To further evaluate the risk/reward characteristics of the forecast, the model includes a built-in table with the following metrics:
Regime = Current market regime based on the selected strategy configuration.
Duration = Percentile rank of current regime duration relative to past regimes.
Forecast = Percentile rank of current duration including the forecast horizon.
Win Rate = Percentage of profitable simulations relative to total simulations.
Profit Factor = Ratio of total simulated profits to total simulated losses.
Expectancy = Average expected percentage return across all simulations.
Reward/Risk = Ratio of upper quartile return to lower quartile return.
Asymmetry = Ratio of selected upper tail return to selected lower tail return.
Skewness = Ratio of upside potential to downside risk relative to the median.
Sample Size = Number of historical returns available for the current regime.
Frequency = Percentage of historical returns belonging to the current regime.
In summary, the Strategy Forecast Engine is a comprehensive forecasting tool designed to help investors evaluate the return distribution of trend-following strategies based on the current market regime. By combining regime detection with Monte Carlo simulation, the model conditions forecasts on historical returns observed during comparable market regimes to estimate the distribution of potential outcomes and their associated risk/reward characteristics. While the model provides valuable insight into historical return patterns, investors should remain mindful that historical market behavior may not necessarily persist under future market conditions. Wskaźnik

TJR v4 StrategyHere's a short publish description:
TJR PRO — Sweep → BOS→ FVG
An ICT-style strategy built on a single model: price raids liquidity, shifts market structure, then returns to the fair value gap for entry.
The model:
Sweep — a liquidity pool gets raided (PDH/PDL, PWH/PWL, Asia/London/NY session highs & lows, EQH/EQL)
MSS — market structure shifts in the opposite direction (displacement break)
FVG — price retraces into the resulting fair value gap (entry at the edge or 50% / consequent encroachment)
Filters & confluence: ADX chop filter, two-sided raid cooldown, manual news blackout, HTF bias (EMA), SMT divergence, midnight-open alignment, killzone timing — combined into an adjustable confluence score.
Risk: 1% risk-per-trade sizing (or fixed contracts), automatic stop beyond the sweep, target cascade to the nearest unswept pool with a fallback R:R.
Adaptive profiles for scalping (1–5m) and intraday (15m–1H). Includes a live info panel and on-chart trade boxes.
Educational tool — not financial advice. Backtest results do not guarantee future performance.
Strategia

NORN WEAVE | THURISAZ# NORN WEAVE ᚦ THURISAZ
---
### Overview
NORN WEAVE ᚦ THURISAZ is the third version of the NORN WEAVE series, built on URUZ as its foundation.
The core logic is unchanged — EMA slope, Dow Theory swing structure, ADX trend confirmation. What changed is the entry filter. THURISAZ adds one question before every trade: *where are we standing on the daily chart?*
URUZ was built to survive. THURISAZ is built to choose. Bad entries don't just lose money — they consume time, margin, and mental bandwidth. The goal of this version is to stop entering trades that look right on the current timeframe but are wrong on the bigger picture.
The philosophy remains: survival first, profit second. THURISAZ adds a third principle — *don't enter where you shouldn't be standing.*
---
### What's New: Daily Fibonacci Filter
THURISAZ introduces a daily timeframe Fibonacci filter as a structural context layer.
When the current timeframe trend and the daily trend align, the strategy behaves exactly like URUZ — no additional friction.
When they diverge, THURISAZ evaluates *where* price sits within the daily swing range using Fibonacci retracement levels (0.382 and 0.618):
- **Mid zone (0.382–0.618)** — Price is in the middle of the daily range. This is the "landing zone": the most likely area for a pullback to stall and reverse, not complete. Entries are blocked.
- **Shallow zone (below 0.382)** — The pullback is still early. Entry is allowed, but TP1 is adjusted to the 0.382 level rather than the standard ATR-based target. Partial profit is taken before the natural resistance zone.
- **Deep zone (above 0.618)** — Price has retraced significantly. Potential reversal territory. Entry is allowed with standard targets.
The daily swing detection period is independently configurable from the current timeframe's Focus Level, giving finer control over what constitutes a "daily swing."
---
### Entry Conditions
**Long:** EMA rising AND Dow Theory trend up AND ADX above threshold AND Daily Fibo zone allows AND Footprint Delta bullish (if filter enabled)
**Short:** EMA falling AND Dow Theory trend down AND ADX above threshold AND Daily Fibo zone allows AND Footprint Delta bearish (if filter enabled)
---
### Exit Conditions
- TP1 — ATR × Factor × 1 → closes 30% (or Fibo 0.382 if shallow counter-trend entry)
- TP2 — ATR × Factor × 2 → closes another 30%
- TP3 — ATR × Factor × 3 → closes a further 30%
- Stop Loss — fixed % from entry → closes full position
- Break Even Stop — once floating profit reaches the BE trigger %, stop moves to entry price and closes on pullback
- Trend Reversal — when Dow Theory swing flips → closes full position
---
### Focus Level & Auto Calibration
Unchanged from URUZ. Focus Level is the primary knob — adjust it first when applying to a new symbol or timeframe.
Auto Calibration computes ADX threshold, ATR factor, and Stop Loss from the chart's own volatility data. When enabled, no manual tuning is required.
---
### Break Even Stop
Unchanged from URUZ. One parameter: how far price must move from entry before the stop activates. Stop is always placed at entry price.
---
### Footprint Delta Filter *(Premium plan required)*
Unchanged from URUZ. Uses BTC or ETH footprint delta as a directional confirmation filter. Blocks entries when order flow contradicts the trade direction.
---
### Parameters
- **Focus Level** (default 13) — Main knob. Controls swing detection and EMA scaling.
- **EMA Scale Ratio** (default 5) — EMA length = Focus Level × this value.
- **Daily Swing Length** (default 10) — Swing detection period for the daily timeframe. Independent from Focus Level.
- **Show Daily Fibo Zone** (default ON) — Displays the 0.382 and 0.618 levels on the chart for visual reference.
- **Auto Calibration** (default ON) — Computes ADX threshold, ATR factor, and SL automatically.
- **BE Trigger %** (default 5.5%) — How far price must move before the BE stop activates.
- **ATR Factor** — Manual mode only. Default 3.8.
- **Stop Loss %** — Manual mode only. Default -10.0%.
- **ADX Threshold** — Manual mode only. Default 20.5.
- **Footprint SMA Period** (default 21) — Smoothing period for delta signal.
---
### On Overfitting
One of the design principles of the NORN WEAVE series has been to minimize the number of configurable parameters. More parameters means more room to fit historical data — and less reason to trust that the results will hold going forward.
THURISAZ adds one new parameter: Daily Swing Length. That's it.
The Fibonacci levels themselves (0.382 and 0.618) are not parameters — they are fixed, widely recognized structural levels used by traders across markets and timeframes. They were not chosen by optimizing against backtest data.
The Daily Fibonacci Filter was validated across six symbols (SOL, DOGE, ETH, SUI, NEAR, PEPE). Five of the six showed improvement in profit factor and drawdown. The one exception — PEPE — deteriorated, which is the expected behavior: PEPE's explosive, non-structural price action doesn't respect daily swing context the way trend-following instruments do. A filter that improves everything uniformly would be suspicious. This result is not.
The filter works because the idea behind it is sound, not because it was tuned to work.
---
### Visual Guide
- **EMA line** — 3-layer glow. Teal when rising, red when falling.
- **Dow Theory zones** — gradient fill from current swing level to current price.
- **Daily Fibo lines** — gold lines at 0.382 and 0.618 of the daily swing. Shaded zone between them marks where entries are blocked.
- **TP lines** — semi-transparent. TP1 faintest, TP3 most visible.
- **BE Stop line** — gold, appears only when active.
- **Gray background** — ADX below threshold. No entries.
- **Orange background** — Footprint Delta Filter blocking entry, or Daily Fibo mid zone active.
- **Status table** — real-time display of all conditions. Japanese/English toggle included. Daily Fibo status shown as: Same Dir / Mid Zone (blocked) / Shallow (TP adjusted) / Deep (reversal watch).
---
---
### 概要
NORN WEAVE ᚦ THURISAZ は、URUZを土台とした NORN WEAVE シリーズ第3バージョンです。
コアロジックは変わっていません——EMAの傾き・ダウ理論のスイング構造・ADXトレンド確認。変わったのはエントリーフィルターです。THURISAZは、すべてのトレードの前に一つの問いを加えます。*日足でみたとき、今どこに立っているのか?*
URUZは「生き残る」ために設計されました。THURISAZは「選ぶ」ために設計されています。悪いエントリーは資金を失うだけでなく、時間・証拠金・集中力を消費します。このバージョンの目標は、現在足ではシグナルが正しく見えても、大きな地形では立ってはいけない場所へのエントリーを止めることです。
哲学は変わっていません。まず生き残る、利益はその次。THURISAZは三つ目の原則を加えます——*立つべきでない場所には立たない。*
---
### 追加機能:日足フィボフィルター
THURISAZは、相場の地形を把握するための「日足フィボナッチフィルター」を新たに導入しました。
現在足のトレンドと日足のトレンドが同じ方向の場合、ストラテジーはURUZとまったく同じ挙動をします——追加の制約はありません。
方向が逆の場合、THURISAZはフィボナッチリトレースメント水準(0.382・0.618)を使い、日足スイングのどの位置に価格があるかを評価します。
- **中間ゾーン(0.382〜0.618)** — 価格が日足レンジの真ん中にある状態。「踊り場」と呼ぶべき位置で、押し目・戻しが途中で止まって反転する可能性が最も高い。エントリーをブロックします。
- **浅いゾーン(0.382以下)** — 押し目・戻しがまだ浅い段階。エントリーは許可しますが、TP1を通常のATRベースから日足フィボ0.382水準に調整します。自然な抵抗ゾーンの手前で部分利確します。
- **深いゾーン(0.618以上)** — 大きく押し込まれた位置。反転の可能性がある水準として通常通りエントリーします。
日足のスイング検出期間は現在足のフォーカスレベルとは独立して設定できます。
---
### エントリー条件
**ロング:** EMA上向き AND ダウ理論上昇 AND ADXしきい値以上 AND 日足フィボゾーン許可 AND フットプリントデルタ買い優勢(フィルター有効時)
**ショート:** EMA下向き AND ダウ理論下降 AND ADXしきい値以上 AND 日足フィボゾーン許可 AND フットプリントデルタ売り優勢(フィルター有効時)
---
### イグジット条件
- TP1 — ATR×倍率×1 → 30%決済(逆張り・浅いゾーン時はフィボ0.382水準)
- TP2 — ATR×倍率×2 → さらに30%決済
- TP3 — ATR×倍率×3 → さらに30%決済
- ストップロス — エントリーから設定%に達したら全決済
- ブレークイーブンストップ — 含み益がBE発動しきい値%に達したらストップが建値に移動。価格が戻ったら全決済
- トレンド反転 — ダウ理論スイングが逆転した時点で全決済
---
### フォーカスレベルとオートキャリブレーション
URUZから変更なし。フォーカスレベルが主軸ノブです。新しい銘柄・時間足に適用するときはここを最初に調整してください。
オートキャリブレーションをONにすると、ADXしきい値・ATR倍率・SLがチャートのボラティリティデータから自動算出されます。
---
### ブレークイーブンストップ
URUZから変更なし。設定項目は一つ——「何%動いたら発動するか」だけ。ストップ位置は常に建値です。
---
### フットプリント・デルタフィルター *(Premiumプラン以上が必要)*
URUZから変更なし。BTCまたはETHのフットプリントデルタを方向性確認フィルターとして使用します。
---
### パラメーター
- **フォーカスレベル**(デフォルト13)— 主軸ノブ。スイング検出・EMAスケールを制御。
- **EMAスケール倍率**(デフォルト5)— EMA期間 = フォーカスレベル × この値。
- **日足スイング検出期間**(デフォルト10)— 日足フィボ計算に使うスイング検出期間。フォーカスレベルとは独立。
- **日足フィボゾーン表示**(デフォルトON)— 0.382・0.618ラインをチャートに表示。
- **オートキャリブレーション**(デフォルトON)— ADXしきい値・ATR倍率・SLを自動算出。
- **BE発動しきい値%**(デフォルト5.5%)— エントリーからこの%動いたらBEストップが発動。
- **ATR倍率**(手動)— オートキャリブレーションOFF時に有効。デフォルト3.8。
- **損切り%**(手動)— オートキャリブレーションOFF時に有効。デフォルト-10.0%。
- **ADXしきい値**(手動)— オートキャリブレーションOFF時に有効。デフォルト20.5。
- **フットプリントSMA期間**(デフォルト21)— デルタシグナルの平滑化期間。
---
### 過剰最適化について
NORN WEAVE シリーズの設計方針の一つは、パラメーター数をできる限り減らすことでした。パラメーターが増えるほど過去データへの過剰適合が起きやすくなり、将来の結果を信頼する根拠が薄れるからです。
THURISAZで追加したパラメーターは「日足スイング検出期間」の一つだけです。
フィボナッチ水準(0.382・0.618)自体はパラメーターではありません——バックテストデータを最適化して選んだ値ではなく、多くのトレーダーが長年にわたって参照してきた普遍的な構造水準です。
日足フィボフィルターは6銘柄(SOL・DOGE・ETH・SUI・NEAR・PEPE)で検証しました。そのうち5銘柄でPFとDDが改善しました。唯一悪化したのはPEPEですが、これは想定内の結果です——PEPEの急騰急落型の値動きは日足スイング構造を参照するロジックとそもそも相性が悪い。すべての銘柄で一様に改善するフィルターの方が、むしろ過剰最適化を疑うべきです。
このフィルターが機能するのは、チューニングの結果ではなく、背後にある考え方が正しいからだと考えています。
---
### チャートの見方
- **EMAライン** — 3層グロー効果。上向きはティール、下向きはレッド。
- **ダウ理論ゾーン** — 現在のスイングレベルから現在価格へのグラデーション。
- **日足フィボライン** — 日足スイングの0.382・0.618をゴールドラインで表示。その間のシェードが「踊り場ゾーン(エントリーブロック)」。
- **TPライン** — 半透明。TP1が最も薄く、TP3が最も濃い。
- **BEストップライン** — ゴールド。発動中のみ表示。
- **グレー背景** — ADXがしきい値以下。エントリーなし。
- **オレンジ背景** — フットプリントデルタフィルターがブロック中、または日足フィボ踊り場ゾーンが有効。
- **ステータステーブル** — 全条件・パラメーター値をリアルタイム表示。日英切り替え対応。日足フィボの状態は「同方向 / 踊り場(ブロック)/ 浅い(TP調整)/ 深い(反転狙い)」で表示。 Strategia

Supertrend Parameter Sensitivity 3D [LuxAlgo]The Supertrend Parameter Sensitivity 3D indicator is a powerful optimization tool that executes 100 simultaneous Supertrend backtests bar-by-bar to visualize how different ATR Lengths and Multipliers impact performance across various metrics.
By projecting this data onto a 3D surface and a heatmap dashboard, it allows traders to identify "stable" parameter zones and avoid over-optimized "peaks" that may lead to curve-fitting.
🔶 USAGE
This tool is designed to help traders find the most robust settings for the Supertrend indicator on any given timeframe or asset. Instead of manually guessing settings, users can see a holistic view of the parameter space.
🔹 3D Surface Projection
The 3D surface is rendered directly on the chart, where the X-axis represents the Multiplier, the Y-axis represents the ATR Length, and the Z-axis (height) represents the chosen performance metric.
Gold Highlight: Marks the absolute "Best" parameter combination based on the selected metric.
Blue Highlight: Marks the "Stable Area," which is the region where the average performance of a 3x3 parameter window is highest. This helps identify settings that remain profitable even if market conditions shift slightly.
🔹 Optimization Dashboard
The dashboard provides a detailed heatmap of the 100 tested combinations.
Value Distribution: An ASCII histogram at the top shows the distribution of all results, helping you understand if the "best" setting is an outlier or part of a consistent trend.
Heatmap Matrix: Displays the exact values for every combination. Hovering over any cell in the table reveals a tooltip with specific data, including the total number of trades for that combination.
Color Scaling: The colors are normalized relatively. Green represents the best results in the current set, while red represents the worst, allowing for clear visual distinction even if all results are negative or positive.
🔶 DETAILS
🔹 Bar-by-Bar Evaluation
The script manages 100 independent Supertrend states simultaneously. On every bar, it calculates the ATR and trailing stop levels for every combination in the sensitivity matrix. It simulates "Always-in-Market" trades (flipping long/short on direction changes) to track performance data without needing a separate strategy execution.
🔹 Optimization Metrics
Users can choose from 9 different metrics to optimize the 3D surface and Dashboard:
Win Rate: Percentage of trades that resulted in a profit.
Net Profit: Total gross profit minus total gross loss.
Profit Factor: Ratio of gross profit to gross loss.
Total Trades: The raw volume of signals generated.
Average Trade: The mean percentage return per trade.
Reward/Risk Ratio: The average win divided by the average loss.
Gross Profit: Total sum of all winning trades.
Total Wins: The absolute count of profitable trades.
Win/Loss Ratio: The count of wins divided by the count of losses.
🔶 SETTINGS
🔹 Main Indicator
ATR Length: The length used for the primary Supertrend line plotted on the chart.
Multiplier: The multiplier used for the primary Supertrend line plotted on the chart.
🔹 Sensitivity Ranges
Length Start: The starting ATR length for the 10x10 matrix.
Length Step: The increment added to the length for each subsequent row.
Multiplier Start: The starting Multiplier for the 10x10 matrix.
Multiplier Step: The increment added to the multiplier for each subsequent column.
🔹 Optimization
Metric: Selects the performance data used to determine the Z-height of the surface and the colors of the heatmap.
🔹 3D Surface Style
High/Low/Wire/Stable Colors: Customize the visual appearance of the 3D projection.
X/Y/Z Spacing & Scale: Adjusts the physical dimensions and height of the 3D surface on the chart.
🔹 Dashboard
Enable Dashboard: Toggles the visibility of the heatmap table.
Position/Size: Controls where the dashboard appears and how large it is on the screen.
Wskaźnik

Wskaźnik

Shift Structure Cloud [JOAT]Shift Structure Cloud is an open-source Pine Script v6 overlay that converts confirmed swing structure into a clean adaptive trend cloud. It tracks pivot highs and pivot lows, separates continuation breaks from character shifts, and uses the active structure range to build a dynamic average and multi-layer cloud around price.
The problem it solves is structural context. Many trend tools react only to moving averages or oscillator thresholds. This script anchors its visual state to confirmed market structure first, then uses an adaptive cloud to show whether price is trading above, below, or inside the current structural center. The result is a chart layer that can help separate continuation from transition without relying on future bars.
Core Concepts
1. Confirmed Pivot Structure
The script uses ta.pivothigh() and ta.pivotlow() to confirm swing highs and lows. A pivot is only accepted after the configured right-side confirmation window closes, which means the level is delayed by design but does not depend on unconfirmed future plotting.
pivotHigh = ta.pivothigh(high, pivotLeft, pivotRight)
pivotLow = ta.pivotlow(low, pivotLeft, pivotRight)
if not na(pivotHigh)
structureHigh := pivotHigh
2. BOS and CHoCH Logic
The current structure high and low become break reference levels. A bullish break occurs when price closes above the prior structure high. A bearish break occurs when price closes below the prior structure low. If the break happens against the previous side, it is classified as CHoCH; otherwise it is a continuation BOS.
bullBreakRaw = barstate.isconfirmed and not na(priorHigh) and close > priorHigh and priorClose <= priorHigh
bearBreakRaw = barstate.isconfirmed and not na(priorLow) and close < priorLow and priorClose >= priorLow
bullChoCh = bullBreak and trendSide == -1
bearChoCh = bearBreak and trendSide == 1
3. Adaptive Structure Average
Instead of plotting only fixed swing levels, the script calculates the midpoint between the active structure high and low. The midpoint is then smoothed with an adaptive alpha. When price moves far from the structural center, the average becomes more responsive; when price is balanced, it becomes slower.
structureMid = (activeHigh + activeLow) * 0.5
structureDrift = f_clamp(math.abs(close - structureMid) / legSize, 0.0, 1.0)
adaptAlpha = slowAlpha + (fastAlpha - slowAlpha) * structureDrift
structureAverage := structureAverage + adaptAlpha * (structureMid - structureAverage )
4. Multi-Layer Cloud
The cloud is built from ATR-adjusted bands around the adaptive structure average. Inner, middle, and outer layers give a visual read of compression, transition, and extended distance from structure.
5. Strength-Based Candle Coloring
When enabled, candles are repainted with a gradient based on distance from the structure average. The candle color is informational only; it does not change the underlying chart data.
Features
Confirmed BOS and CHoCH detection: Structural events are gated with barstate.isconfirmed
Adaptive structure average: A dynamic centerline based on active swing range and price drift
Layered trend cloud: Inner, middle, and outer ATR bands visualize distance from structure
Structure high and low levels: Current confirmed swing levels can be shown as reference lines
Gradient candle mode: Optional candle coloring by structural distance
Compact dashboard: Shows side, last shift, strength, bars since shift, and active range
Palette presets: Aqua Rose, Neon Desk, Mint Pulse, and VWAP Field
Alert conditions: Separate alerts for bullish BOS, bearish BOS, bullish CHoCH, and bearish CHoCH
Input Parameters
Visual System:
Palette Preset: Selects the bull and bear color pair
Color Candles: Enables structural candle coloring
Dashboard: Shows or hides the top-right dashboard
Pivot Dots: Shows confirmed pivot dots
Structure Engine:
Pivot Left / Pivot Right: Controls swing confirmation sensitivity
Fast Adapt Length: Fast smoothing response for the adaptive average
Slow Adapt Length: Slow smoothing response for balanced conditions
Cloud ATR Length: ATR length used for cloud width
Cloud Width: Multiplier applied to the cloud distance
BOS and CHoCH Marks: Shows structural event markers
Structure Levels: Shows active swing high and low reference lines
How to Use This Indicator
Step 1: Read the Cloud Side
If price is above the adaptive structure average and the cloud is colored bullish, the current structural state favors upside continuation. If price is below and the cloud is bearish, the state favors downside continuation.
Step 2: Watch CHoCH Events
CHoCH labels mark breaks against the previous structural side. They are useful as transition warnings, not automatic entries.
Step 3: Use the Structure Levels
The active high and low lines show where the next confirmed break could occur. These are the levels the script uses for BOS and CHoCH classification.
Step 4: Combine with Your Own Trigger
This script is designed as a structure and context layer. Use it with your own entry model, risk plan, and market selection process.
Indicator Limitations
Pivot levels confirm after the right-side pivot window closes, so they are intentionally delayed
A fast reversal can occur before a new pivot is confirmed
Cloud distance is ATR-based, so very low volatility markets can compress the visual bands
The script classifies structure; it does not predict future price movement
Originality Statement
Shift Structure Cloud combines confirmed BOS/CHoCH logic, an adaptive structure midpoint, ATR cloud geometry, and strength-colored candles in one original Pine v6 implementation. The script is not a pasted source clone. It rebuilds structure analysis from public Pine mechanics and adds a distinct visual model around the current swing range.
Disclaimer
This script is provided for educational and informational use only. It is not financial advice or a recommendation to buy or sell any financial instrument. Trading involves substantial risk of loss. Signals and structure readings are based on historical chart data and can be wrong in live market conditions. Always use independent analysis and proper risk management.
-Made with passion by jackofalltrades
Wskaźnik

Strategia
