[Kpt-Ahab] Poor Man's Orderflow Simple AlgoPilotImportant Notice and Risk Warning
The published settings were selected solely based on historical data for the asset and timeframe shown.
The displayed result may be random or over-optimized and cannot automatically be transferred to other assets, timeframes, or future market conditions. Even with the presented settings, the strategy may cause significant losses at any time, including the complete loss of the allocated strategy capital.
This script is intended exclusively for analysis and testing purposes. It does not constitute investment advice or a trading recommendation.
Description
This script uses reused and adapted code components from ** Auto RiskManagement & Backtest System 2.1b** and the ** Poor Mans Orderflow Simulator **.
These components have been combined into a standalone strategy that integrates simplified orderflow signals with position management, risk management, and backtesting functions.
How It Works
The strategy uses a simplified approximation of orderflow. It evaluates the relationship between candle body size and candle range, relative volume, candle direction, and recurring absorption and impulse events.
It does not use actual bid/ask, footprint, Level 2, or order book data.
Depending on the selected signal mode, direct breakouts, confirmed absorption clusters, impulse candles, or combinations of these conditions may generate long and short signals.
Position and Risk Management
The script supports, among other features:
* Long and short positions
* Fixed or trailing stop-loss levels
* Multiple partial profit targets
* Breakeven after the first profit target
* Optional additional entries
* Further entries may also be disabled after the specified total number of losing trades has been reached or when the maximum permitted drawdown is exceeded.
* Internal or external trading signals
* Automatic parameters based on asset class and timeframe
Additional entries and simulated leverage may significantly increase the risk of loss.
Backtest Limitations
Strategy Tester results are based exclusively on historical market data. Real-world results may differ significantly due to commissions, spreads, slippage, liquidity, price gaps, and execution delays.
Past performance is not a reliable indication of future results.
Position Closing Settings
The **Open Position Signals** setting determines how new signals are handled while a position is already open:
* **Wait-End-Deal:** All indicator signals are ignored until the current position has ended.
* **Wait-Signal-Close:** Only explicit signals for closing a long or short position are processed.
* **Wait-Reversal:** An opposing entry signal may also close the current position.
Several closing conditions are available for the integrated orderflow logic. For example, a position may be closed by an opposing impulse, a combination of a cluster and an impulse, or a confirmed opposing entry signal.
Further trading may also be restricted after a specified number of losing trades or when the maximum permitted drawdown is reached.
Trailing Stop, Breakeven, and Liquidation Line
The strategy supports both a fixed stop-loss and a trailing stop. The selected percentage represents the direct price distance from the average entry price and is not automatically adjusted by the simulated leverage.
In trailing mode, the stop is only moved in a direction that is favorable to the position. If the average entry price changes due to an additional entry, the existing stop is adjusted accordingly.
The stop may optionally be moved to the average entry price after the first profit target has been reached. A stop mode must be enabled for this function to operate.
The displayed liquidation line is only an internal estimate based on the simulated position and account values. It may differ significantly from the actual liquidation calculation used by a broker or exchange.
Using External Indicators
An external numerical signal source may be used instead of the integrated Poor Man’s Orderflow Simulator.
The external indicator must provide a selectable plot series containing the following values:
* **+1:** Long or buy signal
* **−1:** Short or sell signal
* **+2:** Close short position
* **−2:** Close long position
All other values, including `na`, produce no new signal.
The external indicator must output the required numerical values through a selectable plot. This plot can then be selected under **External Source**.
Whether and how an external signal is processed while a position is open also depends on the selected **Open Position Signals** setting.
-----------------------------------
Wichtiger Hinweis und Risikowarnung
Die veröffentlichten Einstellungen wurden ausschließlich anhand historischer Daten für das dargestellte Asset und den verwendeten Zeitrahmen gewählt.
Das Ergebnis kann zufällig oder überoptimiert sein und lässt sich nicht automatisch auf andere Assets, Zeitrahmen oder zukünftige Marktphasen übertragen. Auch mit den dargestellten Einstellungen kann die Strategie jederzeit erhebliche Verluste verursachen und das eingesetzte Strategiekapital vollständig verlieren.
Dieses Skript dient ausschließlich zu Analyse- und Testzwecken und stellt keine Anlageberatung oder Handelsempfehlung dar.
Beschreibung
Dieses Skript verwendet wiederverwendete und angepasste Codebestandteile aus Auto RiskManagement & Backtest System 2.1b und dem Poor Mans Orderflow Simulator .
Die Komponenten wurden zu einer eigenständigen Strategie verbunden, die vereinfachte Orderflow-Signale mit Positions-, Risiko- und Backtestfunktionen kombiniert.
Funktionsweise
Die Strategie verwendet eine vereinfachte Annäherung an Orderflow. Sie wertet das Verhältnis von Kerzenkörper und Handelsspanne, relatives Volumen, Kerzenrichtung sowie wiederkehrende Absorptions- und Impulsereignisse aus.
Dabei werden keine echten Bid-/Ask-, Footprint-, Level-2- oder Orderbuchdaten verwendet.
Abhängig vom gewählten Signalmodus können direkte Ausbrüche, bestätigte Absorptionscluster, Impulskerzen oder Kombinationen dieser Bedingungen Long- und Short-Signale erzeugen.
Positions- und Risikomanagement
Das Skript unterstützt unter anderem:
Long- und Short-Positionen
feste oder nachlaufende Stop-Loss-Marken
mehrere Teilgewinnziele
Breakeven nach dem ersten Gewinnziel
optionale zusätzliche Einstiege
Drawdown-Begrenzung und Begrenzung nach einer festgelegten Anzahl an Verlusttrades
interne oder externe Handelssignale
automatische Parameter nach Assetklasse und Zeitrahmen
Zusätzliche Einstiege und ein simulierter Hebel können das Verlustrisiko deutlich erhöhen.
Einschränkungen des Backtests
Die Ergebnisse des Strategietesters basieren ausschließlich auf historischen Kursdaten. Reale Ergebnisse können durch Gebühren, Spread, Slippage, Liquidität, Kurslücken und Ausführungsverzögerungen erheblich abweichen.
Vergangene Ergebnisse sind kein verlässlicher Hinweis auf zukünftige Ergebnisse.
Schließungseinstellungen
Über **Open Position Signals** wird festgelegt, wie neue Signale während einer bereits geöffneten Position behandelt werden:
* **Wait-End-Deal:** Alle Indikatorsignale werden bis zum Ende der Position ignoriert.
* **Wait-Signal-Close:** Nur ausdrückliche Signale zum Schließen einer Long- oder Short-Position werden berücksichtigt.
* **Wait-Reversal:** Zusätzlich kann ein entgegengesetztes Einstiegssignal die aktuelle Position schließen.
Für die integrierte Orderflow-Logik stehen verschiedene Schließungsbedingungen zur Verfügung. Eine Position kann beispielsweise durch einen gegensätzlichen Impuls, eine Kombination aus Cluster und Impuls oder ein bestätigtes entgegengesetztes Einstiegssignal geschlossen werden.
Zusätzlich kann der weitere Handel nach einer festgelegten Anzahl an Verlusttrades oder beim Erreichen des maximal erlaubten Drawdowns begrenzt werden.
Trailing-Stop, Breakeven und Liquidationslinie
Die Strategie unterstützt einen festen Stop-Loss sowie einen nachlaufenden Trailing-Stop. Der eingestellte Prozentwert beschreibt dabei den direkten Abstand zum durchschnittlichen Einstiegspreis und wird nicht automatisch durch den simulierten Hebel verändert.
Im Trailing-Modus wird der Stop nur in eine für die Position günstigere Richtung nachgezogen. Verändert sich der durchschnittliche Einstiegspreis durch einen zusätzlichen Einstieg, wird auch der bestehende Stop entsprechend angepasst.
Optional kann der Stop nach dem Erreichen des ersten Gewinnziels auf den durchschnittlichen Einstiegspreis verschoben werden. Hierfür muss ein Stop-Modus aktiviert sein.
Die angezeigte Liquidationslinie ist lediglich eine interne Schätzung auf Basis der simulierten Positions- und Kontowerte. Sie kann deutlich von der tatsächlichen Liquidationsberechnung eines Brokers oder einer Börse abweichen.
Verwendung externer Indikatoren
Anstelle des integrierten Poor-Man’s-Orderflow-Simulators kann eine externe numerische Signalquelle verwendet werden.
Hierfür muss der externe Indikator eine auswählbare Plot-Serie mit den folgenden Werten ausgeben:
* **+1:** Long- beziehungsweise Kaufsignal
* **−1:** Short- beziehungsweise Verkaufssignal
* **+2:** Short-Position schließen
* **−2:** Long-Position schließen
Bei allen anderen Werten oder bei `na` wird kein neues Signal ausgeführt.
Der externe Indikator muss die benötigten Zahlenwerte direkt über einen auswählbaren Plot bereitstellen. Anschließend wird dieser Plot unter **External Source** ausgewählt.
Ob und wie ein externes Signal während einer geöffneten Position verarbeitet wird, hängt zusätzlich von der gewählten Einstellung unter **Open Position Signals** ab. Strategy

Strategy

Zone Flow S/R StrategyZone Flow S/R Strategy
📌 Strategy Overview
Zone Flow is a multi‑timeframe support/resistance strategy that uses dynamic pivot‑derived zones to identify high‑probability reversal and breakout setups.
Unlike static support/resistance lines, this 9‑level zone system (R4–R1, P, S1–S4) automatically adapts to market structure changes at each new period (Daily/Weekly/Monthly). Each zone has a configurable width (Percentage, ATR, or Fixed) to account for volatility, and a breakout threshold to filter out minor wicks.
# Unique Synergy
Most pivot strategies treat levels as static lines, leading to false breakouts. Most engulfing strategies ignore the bigger picture, catching falling knives. This strategy solves both problems by combining these components in a specific sequence:
1- Dynamic Zones + Gap State Machine (The Context)
Instead of just drawing lines, we create zones (R1-R4, P, S1-S4) with adaptive width. More importantly, the Gap State Machine tracks which gap price sits in (e.g., between R1 and Pivot). This tells us exactly where we are in the market structure. If price moves from upper Gap to lower Gap, the strategy instantly switches sentiment from Bullish to Bearish.
- Why this matters: It prevents the strategy from trading blindly; it only trades when price is transitioning between structural levels, and price retrace to the zone drastically reducing false signals in the middle of nowhere.
2- Pin Bar Sweep + Engulfing Combo (The Momentum Trigger)
A standard pin bar alone is a weak reversal signal. A standard engulfing pattern alone is common. However, when a Pin Bar sweeps the N-bar high/low (proving a breakout attempt failed) and is immediately followed by an Engulfing pattern on the next candle, this combo represents a "double confirmation" of exhaustion.
Crucially, this specific combo overrides the EMA confirmation.
- Why this matters: Strong momentum sweeps often happen against the short-term EMA trend. By allowing this specific combo to bypass the EMA, the strategy captures powerful reversals that pure trend-following strategies miss.
3- Dynamic Zone Width (The Volatility Adaptation)
Instead of using fixed support/resistance, the zone width changes based on the selected Period's ATR or Percentage.
- Why this matters: This ensures the strategy scales perfectly across any asset (Gold, Crypto, Forex) without manual width adjustments, making it robust across different volatility regimes.
4- Selective Zone Activation (The Manual Override)
Unlike standard pivot systems that force trades on every level, the Zone Selection inputs allow users to disable specific zones (e.g., turn off R3 if price often fakes out there or turn off S4 market is always get exhausted lower probability trade).
- Why this matters: This turns the strategy from a rigid algorithm into a customizable framework where the user can apply their own discretion based on historical price behavior.
5. Hierarchical EMA Architecture (The Structural Governor)
This strategy does not treat all EMAs equally. It uses a two-tier EMA system with a strict hierarchy:
Lower TF EMA (Optional & Overrideable): The Lower TF EMA on the current timeframe acts as a micro-trend filter. However, as explained above, the Pin Bar Sweep + Engulfing Combo can override this filter. Why? Because strong institutional reversals often happen against the short-term trend, and we want to capture them.
Higher TF EMA (Absolute & Non-Negotiable): Higher TF EMA on the selected Higher Timeframe acts as an "Absolute Structural Governor." Unlike the lower EMA, this filter cannot be overridden by any pattern.
For Long entries: Price must be above this HTF EMA.
For Short entries: Price must be below this HTF EMA.
Most strategies either ignore the HTF entirely. By making the HTF EMA absolute and the LTF EMA overrideable, this strategy achieves the perfect balance:
The HTF EMA prevents catastrophic drawdowns by keeping you on the right side of the bigger trend.
The LTF EMA override allows you to catch sharp, high-probability reversals within that trend without being delayed by a slow-moving micro-filter.
6. Optional Risk Architecture (The Management Layer)
The strategy includes a built-in partial-take-profit and breakeven module. By default, this module is disabled to provide a clean, straightforward 1:3 risk-reward backtest without the complexity of multiple exit orders.
This default setting allows users to evaluate the core entry logic (zones + patterns) without interference from partial exits.
However, for traders who want to reduce psychological pressure or manage Gold's notorious retracements, they can enable Allow Breakeven and Allow Partial TP. When activated, the strategy closes a percentage of the position (e.g., 50%) at a lower R:R threshold (TP1) and moves the remaining position to breakeven—locking in early profits while letting the rest of the trade run.
# Zone Calculation
The strategy calculates 9 zones using a modified pivot point formula from the selected period (Daily, Weekly, Monthly, Quarterly, Yearly):
The pivot formula can be one of 5 methods: Classic, Fibonacci, Woodie, Camarilla, or DM.
The Classic Pivot (shown below) is the most widely used and serves as the default:
Pivot (P) = (H + L + C) / 3
R1 = (2 × P) – L
S1 = (2 × P) – H
R2 = P + (H – L)
S2 = P – (H – L)
(R3, R4, S3, S4 are logical extensions of this same principle)
Additional Methods (Briefly Explained):
Fibonacci: Uses the golden ratio multipliers (0.382, 0.618, 1.000, 1.618) to place support/resistance levels between the pivot and the high/low range.
Woodie: Gives extra weight to the closing price (Formula: P = (H + L + 2C) / 4), making it more sensitive to the current session's momentum.
Camarilla: Uses multipliers based on the previous range to place levels very close to the current price, ideal for range-bound trading and scalping.
DM: Adjusts the pivot formula conditionally based on whether the close was higher or lower than the open, making it adaptive to daily sentiment.
From these, the strategy derives:
- 4 Resistance Zones (R4, R3, R2, R1) – above the pivot
- 1 Pivot Zone (P)
- 4 Support Zones (S1, S2, S3, S4) – below the pivot
Each zone is expanded by a Zone Width to create a buffer, making the levels more practical.
# Zone Width Calculation
Three modes:
- Percentage – zone width as a percentage of current price
- ATR Multiplier – width = ATR × Multiplier
- Fixed – fixed price distance
# Gap Index Mapping (0–9):
Gap 0 – Above R4 → Aggressive (no trades)
Gap 1 – Between R4 and R3 → Bearish near R4, Bullish near R3
Gap 2 – Between R3 and R2 → Bearish near R3, Bullish near R2
Gap 3 – Between R2 and R1 → Bearish near R2, Bullish near R1
Gap 4 – Between R1 and Pivot → Bearish near R1, Bullish near Pivot
Gap 5 – Between Pivot and S1 → Bearish near Pivot, Bullish near S1
Gap 6 – Between S1 and S2 → Bearish near S1, Bullish near S2
Gap 7 – Between S2 and S3 → Bearish near S2, Bullish near S3
Gap 8 – Between S3 and S4 → Bearish near S3, Bullish near S4
Gap 9 – Below S4 → Aggressive (no trades)
Based on the gap index and price action, the strategy sets allowLong or allowShort – and displays the status on the info table.
Market Status Displayed:
- Bullish – near support zones; long trades allowed
- Bearish – near resistance zones; short trades allowed
- Waiting – new period started; zones recalculating; no trades
- Aggressive – above R4 or below S4; no trades
- Zone disabled – manually disabled zone; no trades
# Entry Signals
1. Engulfing Patterns
Detects bullish and bearish engulfing with filters:
- Body Only – if true, only bodies must engulf (not full range)
- Min/Max Range – can be Percentage, ATR Multiplier, or Fixed
- Gap Allowance – max price gap between previous close and current open
- Previous or Prior Candle – at least one of the last two candles must be the opposite. color (bearish for bullish engulf; bullish for bearish engulf).
This is not a random condition. The strategy only considers trades when price is near a strong structural zone (support/resistance). Because the zone itself provides the primary context for a potential reversal, the immediate previous candle does not need to be strictly opposite in color.By relaxing the requirement to "at least one of the last two," the strategy captures valid reversals at key levels that a strict, textbook rule would miss—while remaining highly selective because it only trades near strong zones.
2. Pin Bar + Engulfing Combo (EMA Override)
Identifies hammers/shooting stars with:
- Wick/Body Ratio (Wick 3× body)Requires a clearly defined pin bar with a very small body.
- Max Body/Range (Body is at most 20% of range) Ensures the body is genuinely small relative to the total range. This is the textbook definition of a pin bar/hammer. Captures true rejection candles.
- Min Wick/Range (70% of range) This is the classic pin bar definition. A 70%+ wick means price aggressively rejected the level and reversed.
- Sweep Lookback – bullish pinbar must break the lowest low of the previous N bars;
bearish must break the highest high
a pin bar that sweeps a recent extreme (lookback) and the very next candle forms an engulfing pattern in the same direction. This combo overrides the Lower TF EMA confirmation – a unique feature that captures strong momentum after a sweep.
Combined Entry Requirements
All of the following must be true:
1. Valid engulfing or pin+engulf combo
2. Pattern occurs near a zone (open inside zone boundaries or crossing it)
3. Market status aligns with trade direction
4. Daily trade limit not exceeded (default: 2)
5. Relevant zone is enabled
6. Price is on the correct side of EMAs (unless overridden by combo)
7. HTF EMA confirms (if enabled)
8. RSI not overbought/oversold (if enabled)
9. Not within the no‑trade window (if enabled)
-----------------------------------------------------
# Confirmation Filters
Current TF EMA – ensures micro‑trend alignment. Overridden by pin+engulf combo.
Higher TF EMA (default 150 on 1H) – filters out counter‑trend moves in the bigger picture.
RSI – prevents buying above 70 and selling below 30.
Bollinger Bands – blocks trades when volatility is too low (BB width below threshold).This filter is specifically designed for assets that range heavily—choppy, sideways markets.
No‑Trade Window – avoids end‑of‑day volatility (active only for timeframes ≤15min).
# Risk & Position Management
1- Position Sizing:
- Risk per trade – percentage of equity for first trade, separate for second
- Position size = (Account Risk) / (Entry – SL distance).
- Second trade does not increment the daily trade counter:
This is a deliberate design choice. The daily trade counter tracks new trade initiations, not total positions. The second trade (pyramiding) is considered a continuation of the existing position, not a new independent decision. This ensures the strategy can scale into strong trends without consuming the daily limit, while still respecting the maximum number of new entries per session.
2-Stop Loss Options:
- Low-High – entry bar low/high ± buffer Tight, reactive stops. Best for scalping or when you want the SL to follow the immediate price action of the entry candle.
- Swing high/low – N-bar low/high ± buffer Broader, structural stops. Ideal for swing trading or when you want the SL to respect recent market structure rather than a single bar.
- Zone – zone boundary ± buffer Structural stops aligned with pivot levels. Best when you want the SL to be placed exactly at the structural support/resistance level that defines the trade.
- Fixed distance – fixed price distance Simple, static stops. Useful when you know your exact risk tolerance in dollar/pip terms and want a consistent SL distance regardless of volatility.
- ATR Multiplier – entry ± (ATR × multiplier) Volatility-adaptive stops. Best for Gold's changing volatility—widens during news/high volatility, tightens during calm periods.
3- Take Profit:
- Main R:R ratio – main R:R ratio (default 1:3), plus optional partial TP and breakeven at a lower R:R ratio.
- Partial TP – close a percentage of position at a lower R:R (TP1)
- Breakeven – optionally move stop to entry at TP1
4- Trade Counter Reset:
- For TF ≤ 15m: resets at NY (9:30 AM) and London (3:30 AM) starts (configurable)
This aligns with Gold's session-specific volatility and allows fresh participation in each session while preventing over-trading within a single session.
- For TF > 15m: resets once per day at session start (Every new day) Session-specific behavior is less relevant on higher timeframes, and a simple daily cap is more appropriate for swing trading.
5- No‑Trade Window:
- Avoids high‑volatility periods (e.g., end of day)
- Active only for TF ≤ 15m (16:00 PM – 18:30 PM NY time, configurable) End-of-day volatility spikes can cause excessive slippage and erratic price action on short timeframes. on TF > 15 The window is too short to be meaningful; higher timeframe traders are less affected by brief volatility spikes.
6- Session Close:
- TF ≤ 15m: can close at day end and/or week end (configurable). Scalping trades on 1m–15m charts typically last minutes to a few hours. These trades are highly sensitive to Overnight gaps, Weekend gaps
- 15m < TF ≤ 10h: only week end. Swing trading on 30m–4H charts typically lasts hours to several days.
- TF > 10h: feature disabled. Position trading on daily+ charts lasts days to weeks. These trades aim to capture large macro moves.
# Chart Display
- Zone boxes – semi‑transparent red/pink with labels (R4…S4), auto‑cleanup (max 55 periods)
- Trade management lines – entry (white), SL (red), TP (green), TP1/breakeven (dashed),
with green/red fills; auto‑cleanup ((4) * max 125)
- Info table (top‑right) :
1. shows Market Status(Bullish/Bearish/Aggressive/Waiting).
2. EMA confirmations.
3. Zone Width, Breakout threshold.
4. Engulf range max min.
5. SL settings(SL refrence, sL bufer)
- EMA plots – light blue (lower TF) and light red (higher TF)
- Signal shapes – hidden by default (can be enabled via style settings)
- arrowdown shapes - "Reset trade counter"
- Background 1 color – yellow during no‑trade window
- Background 2 color – white close all position on week/day end.
UI Note: Inputs are hidden from the status line to keep your chart clean. All settings (zones, EMAs, risk, patterns) remain fully adjustable in Settings → Inputs.
# Default Settings – Optimized for XAUUSD (Gold)
All default values have been calibrated specifically for Gold's typical volatility and intraday structure.
(Setting : Default : Why This Works for Gold)
----------------------------------------------------------------------------------------
Period : Daily : Gold respects daily highs/lows as key structural levels.
-----------------------------------------------------------------------------------------
Pivot Type : Classic : Most widely used and reliable for Gold.
-----------------------------------------------------------------------------------------
Zone Width : ATR (0.053× ATR(14)) : ATR(14) provides a stable, week-to-week view of Gold's volatility (roughly two trading weeks of data).Adapts to Gold's daily volatility (Zone Width often $4–$10 range).
-----------------------------------------------------------------------------------------
Breakout Threshold : 7% of zone width : Zone width ≈ $3.00–$10.00 (Daily ATR × 0.053). 7% ≈ $0.21–$0.70 (21–70 ticks)—filters noise wicks, captures genuine breaks.Prevents false transitions caused by standard stop-hunting wicks
-----------------------------------------------------------------------------------------
Engulfing Range : ATR(14) (0.375× – 2.5×) : ATR(14) sits in the "sweet spot"—responsive enough to capture shifts in Gold's volatility relatively quickly, yet long enough to smooth out the daily noise and provide a reliable, consistent measure. Captures meaningful moves $3–$15—ensures candle has enough size to be meaningful, rejecting tiny $0.30–$0.50 noise patterns, while filtering out massive blow-off spikes (> $20–$25 on 15m).
-----------------------------------------------------------------------------------------
Pin Bar Sweep : 12 bars : 12 bars – Calibrated for Gold's 3-hour intraday cycle and session transitions. Long enough to capture genuine liquidity grabs, short enough to avoid outdated levels.
-----------------------------------------------------------------------------------------
Risk per trade : 2% (1st), 1% (2nd) : Balances risk with Gold's occasional false breakouts. For Gold's volatile nature, 2%-1% provides the best balance between survival and growth.
-----------------------------------------------------------------------------------------
Risk:Reward : 1:3 : Gold routinely moves 1.5–2× its ATR in a single directional push. A 1:3 target is well within Gold's typical daily range.
-----------------------------------------------------------------------------------------
Stop-Loss Reference : ATR Multiplier : For Gold's volatile nature, a static stop-loss (Fixed or Low-High) cannot adapt to changing volatility. ATR-based SL scales with market conditions—widening during high volatility (news, session opens) and tightening during calm periods. This ensures the stop-loss is always "fair" relative to current market conditions, preventing premature stops during normal volatility spikes
-----------------------------------------------------------------------------------------
Stop-Loss Multiplier : 1.8× ATR(14) : A 1.8× ATR(14) stop-loss represents 1.8 times Gold's average 14-period range. Why 1.8× and not 2.0× or 1.5×? Backtesting revealed that 1.8× is the "sweet spot"—wide enough to survive Gold's normal volatility spikes without being stopped out by noise, yet tight enough to limit losses
-----------------------------------------------------------------------------------------
Current TF EMA : 21 (Enabled, Overrideable) : On 15m chart = 5.25 hours—perfectly captures Gold's average intraday move length. Can be overridden by Pin Bar + Engulfing Combo to catch institutional reversals that occur against the short-term trend.
-----------------------------------------------------------------------------------------
Higher TF EMA : 150 on 1H : On Gold, a 150-period EMA on a 1H chart represents roughly 6.5 days (one full trading week) of data. By making this filter absolute, the strategy guarantees it will never take a counter-trend trade against the weekly macro-structure.trend.
-----------------------------------------------------------------------------------------
Filter (RSI) : length 12 : Most traders default to RSI(14), but RSI(12) is intentionally faster for Gold's volatile intraday moves. Gold often spikes into overbought/oversold territory and reverses quickly. A 12-period RSI reacts ~15% faster than RSI(14), catching these reversals earlier while remaining smooth enough to avoid excessive whipsaws.
-----------------------------------------------------------------------------------------
Filter (Bollinger Bands) : Disabled by default : Gold is historically a trending asset with strong directional moves. A low-volatility filter would unnecessarily block valid entries during these trends. Designed for range-bound assets (choppy crypto, certain forex crosses)—enable it only if your market consolidates heavily.
-----------------------------------------------------------------------------------------
These values are a starting point – you may adjust them for other assets or personal risk tolerance.
# Important Notes on Backtest Realism
- Commission – Most ECN/raw-spread brokers charge $3.00–$3.50 per side (round-turn commission of $6.00- $7.00) for 1 standard lot (100 oz) of XAUUSD. Standard accounts usually build the fee into a wider spread instead of charging a separate cash. This strategy deducts $3.50 per entry and $3.50 per exit ($0.035 × 100 oz)round-turn commission of $7.00. Adjust this to match your broker's exact fees.
- 4 ticks Slippage - For XAUUSD, 1 tick = $0.01 per ounce. 4 ticks = **$0.04 per ounce (unit)**. Accounts for real-world price . Prevents overly optimistic backtest equity curves.
Always adjust the commission value to your broker's exact fee structure before relying on the results.
"A backtest without realistic commission and slippage is a fantasy. A backtest with realistic commission and slippage is a truthful reflection of what you can expect when trading live."
- Intra-Bar Execution: The strategy uses calc_on_every_tick = true, meaning it recalculates on every price tick during real-time trading. This allows the breakeven and partial TP logic to trigger immediately when price hits TP1, protecting the trade from intra-bar reversals.
Note: Backtests use OHLC data only, so intra-bar fills and breakeven triggers cannot be perfectly simulated. Real-time performance may differ from backtest results due to this limitation
# The Core Innovation (Why This Isn't Just a Mashup)
This strategy is built on a three-layer validation system. Each layer solves a specific problem that the other layers cannot solve alone.
Layer 1 (The Structure): Dynamic Pivot Zones
Layer 2 (The Trigger): Pin-Bar Sweep + Engulfing Combo
Layer 3 (The Execution): Gap State Machine
Here is how they interdepend to create a unique edge:
1. Adaptive Pivot Mathematics (The "Regime Matching" Logic)
Instead of offering multiple pivot types just for the sake of it, this strategy provides them so the trader can match the mathematical formula to the market's current behavioral regime:
Why this matters: Most strategies lock you into one formula. This strategy acknowledges that price dynamics change, and it gives you the mathematical weapon to adapt without rewriting the entire code.
2. The "Liquidity Grab" Trigger (Sweep + Engulfing Combo)
This is the most critical edge of the strategy. A standard Engulfing pattern is common. A standard Pin Bar is common. But when they occur sequentially—a Pin Bar that sweeps the 12-bar extreme, immediately followed by an Engulfing candle—it represents a textbook institutional "liquidity grab."
- The Logic: Large players often push price to sweep obvious stop-losses (above highs or below lows) before reversing the trend.
- The Override: Crucially, this specific combo overrides the Lower TF EMA confirmation.
- Why this is a breakthrough: Standard trend-following strategies with a hard EMA filter will miss these reversals because price is moving against the EMA in the short term. By programming this specific override, the strategy captures the exact moment of institutional reversal—catching the move before the EMA flips and the trend-followers finally enter.
3. The Gap State Machine (Dynamic Sentiment Tracking)
Unlike static support/resistance scripts that just plot lines and wait for touches, this strategy features a state machine that tracks which of the 9 gaps (between R4-R1, Pivot, S1-S4) the price currently occupies.
- The Mechanism: A Breakout Threshold (default 7% of zone width) acts as a "dead-zone" filter. Price must exceed this threshold to officially transition from one gap to another.
- The Alpha: This prevents the strategy from whipsawing during minor noise. When price crosses from Gap 4 (between R1 and Pivot) into Gap 3 (between R2 and R1), the strategy instantly and autonomously switches market status from "Bearish" to "Bullish" or vice versa.
4. Selective Zone Activation (Strategic Discretion)
- This strategy allows the user to completely disable specific zones (e.g., turn off R3).
- The Value: By disabling a weak level, the user forces the strategy to wait for the next stronger level, instantly increasing the win rate and filtering out historically weak signals without altering any other code.
5. Non-Invasive Risk Architecture (Clean Defaults)
For traders who want to reduce psychological pressure or optimize for Gold's notorious retracements, they can enable these modules. When activated, the strategy closes % of the position at a lower R:R threshold and moves the remaining position to breakeven—locking in profits while letting the rest run.
In Summary: The "Mashup" Justification
This is not a random collection of indicators.
1. The State Machine provides the structural context.
2. The Pin+Engulf combo provides the high-conviction trigger that overrides slow-moving filters.
3. The Selectable Pivot Types provide the mathematical adaptability to different assets.
4. The Selectable Zones provide the manual discretion to avoid historical losing levels.
5. The Disabled TP/BE by default provides a clean baseline for evaluating the core logic.
Author: Awab_Hassan
Strategy

Indicator

Universal Signal Backtester [LuxAlgo]The Universal Signal Backtester indicator is a tool designed to simulate and analyze the performance of virtually any trading signal, ranging from moving average crossovers to external indicator triggers. By providing a professional-grade backtesting environment directly on the chart, it allows users to optimize entry logic, exit strategies, and cost management in real-time.
🔶 USAGE
The script operates by selecting a Source Mode to define how trades are initiated. Users can choose between built-in MA crosses, external source crossovers, or discrete signal triggers from other indicators. Once a signal is detected, the script simulates a trade using up to three Take Profit (TP) and three Stop Loss (SL) levels.
🔹 Trade Visualization
* Sign Posts: Upon entry, the script plots a "Sign Post" label below or above the bar. This label dynamically suggests which TP level is currently the most effective based on the selected metric (e.g., Hit Rate or Expected Profit).
* Active Exit Lines: Horizontal dashed lines extend from the entry point to visualize the selected TP and SL targets. These lines update in real-time and mark hits with a checkmark (✓) or an "X" (✗).
* MA Ribbon: When using predefined crosses, a gradient ribbon is displayed to visualize the trend strength and crossover points.
🔹 Signal Modes
* Predefined Crosses: Quickly test standard strategies like the 9/21 EMA, 12/26 EMA, or the Golden/Death Cross (50/200 SMA).
* External Sources (Crossovers): Select two external plots (e.g., RSI and a level, or two custom MAs) to test their crossover performance.
* External Signals (Triggers): Connect the script to discrete signals such as Plotshapes or Boolean conditions. This is ideal for testing "Buy" and "Sell" signals from specialized indicators.
🔶 DETAILS
🔹 Advanced Analytics Dashboard
The indicator features a robust dashboard providing institutional-level metrics:
* Core Metrics: Total trades, Win Rate, Profit Factor, Sharpe Ratio, and Recovery Factor.
* Equity Curve: A sparkline representation of the account growth over time.
* Hourly Histogram: A performance breakdown by the hour of the day, helping identify the most profitable trading sessions.
* Heatmaps: A "Days of the Week" or "Monthly" heatmap that colors cells based on profitability, allowing for the identification of seasonal or periodic performance patterns.
🔹 Cost Simulation
To ensure realistic results, the script includes a cost engine. Users can select from profiles like Forex, Crypto, or Stocks to automatically apply industry-standard spreads and commissions, or input manual values to match a specific broker's fee structure.
🔶 SETTINGS
🔹 Source Settings
Source Mode: Determines the logic for trade entries (Predefined, External Crossover, or External Trigger). Signal Logic: Defines how external triggers are interpreted (e.g., Value Changes, Crosses 0, or Not NA). Trade Direction: Filters signals to allow only Longs, only Shorts, or Both.
🔹 Filters
Use ATR Choppiness Filter: When enabled, the script ignores signals that occur during low-volatility "choppy" periods.
🔹 Target Settings
Distance Type: Sets the measurement unit for TP/SL levels (ATR, Ticks, or Points). Take Profit (1-3): Toggles and sets the distance for up to three partial take-profit levels. Stop Loss (1-3): Toggles and sets the distance for up to three stop-loss levels.
🔹 Costs
Simulate Spread & Commission: Enables the cost engine for more realistic PnL calculations. Cost Profile: Presets for Forex, Crypto, and Stocks, or "Manual" for custom inputs.
🔹 Dashboard & Visuals
Heatmap Period: Switches the dashboard heatmap between "Days of Week" and "Months". Suggested TP Metric: Chooses the criteria the "Sign Post" uses to suggest the best TP level. Gradient Candle Coloring: Colors candles based on the distance between the fast and slow sources. Indicator

Indicator

[Kpt-Ahab] Moving Average Simple AlgoPilotImportant Notice and Risk Warning
The published settings were selected exclusively based on historical data for the asset and timeframe shown.
The displayed result may be random or over-optimized and cannot automatically be transferred to other assets, timeframes, or future market conditions. Even with the presented settings, the strategy may cause significant losses at any time, including the complete loss of the allocated strategy capital.
This script is intended exclusively for analysis and testing purposes. It does not constitute investment advice or a trading recommendation.
Description
This script uses reused and adapted code components from ** Auto RiskManagement & Backtest System 2.1b** and the ** Moving Average Alarm Output **.
These components have been combined into a standalone strategy that integrates moving-average signals with position management, risk management, and backtesting functions.
How It Works
The strategy uses two freely configurable moving averages. **SMA, EMA, WMA, VWMA, or HMA** can be selected independently for the short and long moving averages.
A long signal is generated when the short moving average crosses above the long moving average. A short signal is generated when the short moving average crosses below the long moving average.
The moving averages are displayed directly on the chart. An additional colored area visualizes the position of the price relative to the long moving average. Its intensity changes according to the distance between the two moving averages.
Position and Risk Management
The script supports, among other features:
* Long and short positions
* Fixed or trailing stop-loss levels
* Multiple partial profit targets
* A final profit target
* Breakeven after the first profit target
* Optional additional entries
* Drawdown and losing-trade limits
* Internal or external trading signals
* Different position-sizing methods
Additional entries and simulated leverage may significantly increase the risk of loss.
Backtest Limitations
Strategy Tester results are based exclusively on historical market data. Real-world results may differ significantly due to commissions, spreads, slippage, liquidity, price gaps, and execution delays.
Past performance is not a reliable indication of future results.
Signals During an Open Position
The **Open Position Signals** setting determines how new signals are handled while a position is already open:
* **Wait-End-Deal:** All new moving-average signals are ignored until the current position has been closed by a profit target, stop-loss, or another protective function.
* **Wait-Reversal:** An opposing moving-average signal may close the currently open position.
With **Wait-Reversal**, a sell signal closes a long position, while a buy signal closes a short position. The opposing signal does not automatically open a new position during the same step.
Price-based additional entries remain independent of this setting and may still be executed when enabled.
Stop-Loss, Trailing Stop, Breakeven, and Liquidation Line
The strategy supports both a fixed stop-loss and a trailing stop. The selected percentage represents the direct price distance from the average entry price and is not automatically adjusted by the simulated leverage.
In **FIXED %** mode, the stop is calculated from the current average entry price. If the average entry price changes due to an additional entry, the stop is recalculated accordingly.
In **TRAILING** mode, the stop only moves in a direction that is favorable to the position. If the average entry price changes due to an additional entry, the existing trailing stop is adjusted accordingly.
The stop may optionally be moved to the average entry price after the first profit target has been reached. A stop mode must be enabled for this breakeven function to operate.
The displayed liquidation line is only an internal estimate based on the simulated position and account values. It may differ significantly from the actual liquidation calculation used by a broker or exchange.
Using External Indicators
An external numerical signal source may be used instead of the integrated moving-average signals.
The external indicator must provide a selectable plot series containing the following values:
* **+1:** Long or buy signal
* **−1:** Short or sell signal
All other values, including `na`, produce no new signal.
The external indicator must output the required numerical values through a selectable plot. This plot can then be selected under **External Source**.
How an external signal is processed while a position is already open also depends on the selected **Open Position Signals** setting.
Wichtiger Hinweis und Risikowarnung
Die veröffentlichten Einstellungen wurden ausschließlich anhand historischer Daten für das dargestellte Asset und den verwendeten Zeitrahmen gewählt.
Das Ergebnis kann zufällig oder überoptimiert sein und lässt sich nicht automatisch auf andere Assets, Zeitrahmen oder zukünftige Marktphasen übertragen. Auch mit den dargestellten Einstellungen kann die Strategie jederzeit erhebliche Verluste verursachen und das eingesetzte Strategiekapital vollständig verlieren.
Dieses Skript dient ausschließlich zu Analyse- und Testzwecken und stellt keine Anlageberatung oder Handelsempfehlung dar.
Beschreibung
Dieses Skript verwendet wiederverwendete und angepasste Codebestandteile aus ** Auto RiskManagement & Backtest System 2.1b** und dem ** Moving Average Alarm Output **.
Die Komponenten wurden zu einer eigenständigen Strategie verbunden, die Moving-Average-Signale mit Positions-, Risiko- und Backtestfunktionen kombiniert.
Funktionsweise
Die Strategie verwendet zwei frei konfigurierbare gleitende Durchschnitte. Für den kurzen und den langen Moving Average können jeweils **SMA, EMA, WMA, VWMA oder HMA** ausgewählt werden.
Ein Long-Signal entsteht, wenn der kurze Moving Average den langen Moving Average von unten nach oben kreuzt. Ein Short-Signal entsteht bei einer Kreuzung von oben nach unten.
Die Moving Averages werden direkt im Chart dargestellt. Eine zusätzliche farbliche Fläche visualisiert die Position des Kurses relativ zum langen Moving Average. Die Intensität der Darstellung verändert sich abhängig vom Abstand zwischen den beiden Moving Averages.
Positions- und Risikomanagement
Das Skript unterstützt unter anderem:
* Long- und Short-Positionen
* feste oder nachlaufende Stop-Loss-Marken
* mehrere Teilgewinnziele
* ein abschließendes Gewinnziel
* Breakeven nach dem ersten Gewinnziel
* optionale zusätzliche Einstiege
* Drawdown- und Verlustserienbegrenzungen
* interne oder externe Handelssignale
* unterschiedliche Methoden zur Bestimmung der Positionsgröße
Zusätzliche Einstiege und ein simulierter Hebel können das Verlustrisiko deutlich erhöhen.
Einschränkungen des Backtests
Die Ergebnisse des Strategietesters basieren ausschließlich auf historischen Kursdaten. Reale Ergebnisse können durch Gebühren, Spread, Slippage, Liquidität, Kurslücken und Ausführungsverzögerungen erheblich abweichen.
Vergangene Ergebnisse sind kein verlässlicher Hinweis auf zukünftige Ergebnisse.
Signale während einer offenen Position
Über **Open Position Signals** wird festgelegt, wie neue Signale während einer bereits geöffneten Position behandelt werden:
* **Wait-End-Deal:** Alle neuen Moving-Average-Signale werden ignoriert, bis die aktuelle Position durch ein Gewinnziel, einen Stop-Loss oder eine andere Schutzfunktion beendet wurde.
* **Wait-Reversal:** Ein entgegengesetztes Moving-Average-Signal kann die aktuell geöffnete Position schließen.
Bei **Wait-Reversal** schließt ein Verkaufssignal eine Long-Position und ein Kaufsignal eine Short-Position. Das entgegengesetzte Signal eröffnet dabei nicht automatisch im selben Schritt eine neue Position.
Preisbasierte zusätzliche Einstiege bleiben von dieser Auswahl unabhängig und können weiterhin ausgeführt werden, sofern sie aktiviert sind.
Stop-Loss, Trailing-Stop, Breakeven und Liquidationslinie
Die Strategie unterstützt einen festen Stop-Loss sowie einen nachlaufenden Trailing-Stop. Der eingestellte Prozentwert beschreibt den direkten Kursabstand zum durchschnittlichen Einstiegspreis und wird nicht automatisch durch den simulierten Hebel verändert.
Im Modus **FIXED %** wird der Stop anhand des aktuellen durchschnittlichen Einstiegspreises berechnet. Verändert sich dieser durch einen zusätzlichen Einstieg, wird auch der Stop neu berechnet.
Im Modus **TRAILING** wird der Stop nur in eine für die Position günstigere Richtung nachgezogen. Verändert sich der durchschnittliche Einstiegspreis durch einen zusätzlichen Einstieg, wird der bestehende Trailing-Stop entsprechend angepasst.
Optional kann der Stop nach dem Erreichen des ersten Gewinnziels auf den durchschnittlichen Einstiegspreis verschoben werden. Für diese Breakeven-Funktion muss ein Stop-Modus aktiviert sein.
Die angezeigte Liquidationslinie ist lediglich eine interne Schätzung auf Basis der simulierten Positions- und Kontowerte. Sie kann deutlich von der tatsächlichen Liquidationsberechnung eines Brokers oder einer Börse abweichen.
Verwendung externer Indikatoren
Anstelle der integrierten Moving-Average-Signale kann eine externe numerische Signalquelle verwendet werden.
Der externe Indikator muss eine auswählbare Plot-Serie mit den folgenden Werten bereitstellen:
* **+1:** Long- beziehungsweise Kaufsignal
* **−1:** Short- beziehungsweise Verkaufssignal
Bei allen anderen Werten oder bei `na` wird kein neues Signal ausgelöst.
Der externe Indikator muss die benötigten Zahlenwerte direkt über einen auswählbaren Plot ausgeben. Dieser Plot kann anschließend unter **External Source** ausgewählt werden.
Wie ein externes Signal während einer bereits geöffneten Position verarbeitet wird, hängt zusätzlich von der gewählten Einstellung unter **Open Position Signals** ab.
Strategy

MACD Pro: Presets by Trading Style with Trend and Chop Filters-------DESCRIPTION
There is no single best MACD setup. The right one depends on your timeframe and on how you trade.
Gerald Appel built the indicator around 12, 26 and 9 for daily and weekly charts. Put those numbers on a fast intraday chart and the signal lags behind the price action. MACD Pro carries the tested setup for each trading style, and it will pick one for you based on the chart you are on.
----------THE PRESETS
Swing (4H, daily, weekly) uses 12, 26 and 9. This is the original setup. It finds macro trends and major reversals without catching every bit of market noise.
Day trading (5m, 15m, 1H) uses 8, 17 and 9. Balanced responsiveness. It cuts the lag on intraday charts while keeping enough smoothing to avoid constant whipsaws.
Intraday momentum (3m, 5m) uses 5, 13 and 1. Dropping the signal length to 1 turns the signal into a direct zero-line cross, which is the sweet spot for catching quick intraday momentum pushes.
Scalping (1m, 3m) uses 3, 10 and 1. Maximum sensitivity to short-term price bursts. High frequency and noisy, so it demands strict risk management.
"Auto by timeframe" reads your chart and loads the right setup for you. Move from a 5-minute chart to a daily chart and the settings follow you. Custom is there when you want your own numbers.
-----------WHY A SIGNAL LENGTH OF 1 IS HANDLED DIFFERENTLY
An exponential average of one period returns the input unchanged. That means at a signal length of 1, the signal line sits exactly on top of the MACD line and a crossover can never fire.
In that mode the script hides the signal line and switches the trigger over to the zero-line cross. The table on the pane tells you which mode is running.
--------------THE FILTERS
200 EMA trend filter. Longs only while price is above the 200 EMA, shorts only while price is below it. A crossover that passes prints a solid triangle. A crossover that fails prints a hollow circle, so you still see that it happened and can judge it yourself.
Chop filter. The MACD is a trend-following momentum tool. In a sideways range, crossovers fire over and over, and every one of them is a whipsaw. When ADX sits under your threshold, the pane shades gray and crossovers are marked as failed. Rely on crossovers only when price is expanding or breaking out.
----------------THE HISTOGRAM AS AN EARLY WARNING
The histogram measures the distance between the MACD line and the signal line. When those bars start shrinking toward zero, momentum is exhausting, even before any crossover happens.
Bars print bright while the histogram is expanding and fade to translucent while it is contracting. A bright green run turning pale is your cue to tighten stops or take something off the table. Yellow dots mark two shrinking bars in a row if you want it called out explicitly.
--------------PAIR IT WITH STRUCTURE
Never take a MACD entry on its own. Line the signals up with breaks of support and resistance, or with an opening range breakout backed by above-average volume. The more elements in agreement, the more confidence you can carry into the trade.
---------------ALERTS
- Filtered bullish signal
- Filtered bearish signal
- Upside momentum exhausting
- Downside momentum exhausting
-----------------NOTES
Written in Pine Script version 6. Every setting is editable, so nothing here is locked to my preferences.
Indicator

Market Structure Shift [JOAT]═══ MARKET STRUCTURE SHIFT ═══
A complete Smart Money Concepts structure engine that reads the market the way institutional flow moves it — mapping every swing and internal shift, tagging each break as BOS (continuation) or CHoCH (reversal), then layering liquidity, premium/discount context, and a structure-anchored risk plan on top. It turns raw price action into a clean, labelled map of who is in control and where the shift happens.
▎ WHAT IT DOES
MSS tracks confirmed pivots and runs them through a two-layer structure state machine. When price closes (or wicks) beyond a protective swing, it draws the break line, labels it BOS or CHoCH, and updates the live trend state. Around that skeleton it adds equal-high/low liquidity marks, a premium/discount/equilibrium range map, an optional structure-anchored SL and Reward:Risk target zone, session VWAP with deviation bands, and a live dashboard summarising the whole picture.
▎ HOW IT WORKS
• Confirmed pivots — swing highs/lows are detected with a symmetric pivot length (bars each side), so a pivot only prints once fully confirmed. A separate, shorter internal pivot length tracks a faster inner structure layer.
• BOS vs CHoCH logic — each layer holds a trend state (bull / bear / range). A bullish break of the last swing high while the state is already bullish is a BOS (continuation); a bullish break while the state was bearish is a CHoCH (change of character / first reversal). The mirror logic applies to bearish breaks.
• Break confirmation — you choose whether a candle must close beyond the level (cleaner) or whether any wick penetration counts.
• Sequence read — every new pivot is classified HH / LH / HL / LL (or EQ) so you can see the higher-high / lower-low rhythm at a glance.
• Liquidity (EQH/EQL) — two consecutive pivots landing within an ATR-scaled tolerance are marked as Equal Highs or Equal Lows — resting liquidity pools where stops cluster.
• Premium / Discount — the active swing range is split into a Premium (upper) zone, a neutral Equilibrium band around the midpoint, and a Discount (lower) zone, so you always know which half of the range price is trading in.
• Structure-anchored risk — on a fresh signal the stop is placed just beyond the swing that would invalidate the shift (plus an ATR buffer), or by a fixed ATR distance. Risk is floored and capped by ATR, and the target is projected at your Reward:Risk multiple.
• VWAP magnet — session-anchored VWAP with inner and outer standard-deviation bands acts as the fair-value reference the structure tends to rotate around.
• ATR normalisation — label spacing, liquidity tolerance and stop distances all scale with ATR, so the tool behaves consistently across assets and timeframes.
▎ HOW TO USE IT
• Read the trend state first: a CHoCH warns the prevailing structure has broken; a following BOS confirms the new leg. Trade with the higher-conviction swing layer and use internal breaks for earlier, finer entries.
• BUY / SELL labels fire on the events you enable (CHoCH, BOS, or both) from your chosen layer — treat them as a structure trigger, not a blind entry.
• Favour longs from the Discount zone and shorts from the Premium zone; the Equilibrium band is neutral / no-man's-land.
• EQH/EQL marks show where liquidity rests — price often sweeps these before a genuine shift, so use them as targets and as traps to avoid.
• When a signal prints, the RISK ZONE (entry→stop, red) and TARGET ZONE (entry→TP, green) boxes project the plan; the SL and TP lines carry exact price and R labels. The zones extend live, then freeze once TP, SL, or the time-out is reached.
• Use VWAP and its bands as confluence — a shift back through VWAP into the opposite σ band is a common rotation target.
▎ KEY SETTINGS
• Structure Engine — swing pivot length, optional internal layer + its length, close/wick break confirmation, ATR length.
• Signals — signal source (Swing / Internal / both) and whether labels fire on CHoCH, BOS, or both.
• Liquidity & Zones — toggle EQH/EQL, equal-level tolerance, premium/discount zones, equilibrium band width, and the floating price-zone tag.
• Risk Model — stop basis (Structure+Buffer or ATR Multiple), buffer/ATR distance, Reward:Risk multiple, min/max risk floors and caps, projection length, max drawn setups.
• VWAP — show VWAP, inner/outer σ multiples, deviation lookback.
• Visuals — swing/internal break display, pivot markers, zone candle colouring, draw limits, and the blue/violet colour scheme.
▎ DASHBOARD
A compact blue/violet panel reports live: overall Trend , the Last Event (Bull/Bear BOS or CHoCH), the current Swing Sequence (e.g. HH · HL), the Internal structure state, the active Price Zone , running BOS and CHoCH counts, Liquidity (EQH/EQL) count, the current Signal , and the symbol/timeframe. Position and text size are adjustable.
▎ ALERTS
Six alertconditions are provided: Bullish BOS, Bearish BOS, Bullish CHoCH, Bearish CHoCH, BUY Signal, and SELL Signal — each with a ready message carrying ticker and interval.
▎ NOTES
• Works on all timeframes and all assets — everything scales with ATR.
• Pivots are confirmed (they need bars to close each side), so structure marks are non-repainting once printed; the price-zone label and dashboard update live on the last bar as expected.
• Every visual layer has a toggle — turn off what you don't need for a clean chart.
• Signals never fire both directions on the same bar; a conflicting wide-range bar is dropped.
For research and education only. This is not financial advice. No indicator can predict the future, and past behaviour does not guarantee future results. Any labels, zones, or counts describe historical price action only. Always do your own analysis and manage your own risk.
Made with passion by JackOfAllTrades ⚡ Indicator

Reactive Trail System [WillyAlgoTrader]📊 Reactive Trail System (RTS) is an overlay trend-following indicator that combines a momentum-adaptive trailing stop, a dual volatility engine, a 0–100 signal quality score, and a complete trade-management layer (Entry / SL / TP1–TP3 / break-even) — all tracked live on a sectioned dashboard with win-rate statistics.
The core insight: a trailing stop should not have a fixed width. When momentum is strong, price moves cleanly and the trail can hug price to lock in profit. When momentum fades, price gets noisy and the trail must widen to survive the chop. RTS measures momentum every bar and reshapes the trail width automatically — up to 40% tighter in strong moves — so one setting adapts to changing conditions instead of being permanently too tight or too loose.
If you are new to trailing stops: think of the trail as a colored line that follows price from below in an uptrend (green) and from above in a downtrend (red). As long as price stays on the right side of the line, the trend is alive. When price closes through the line, the trend flips — and RTS turns that flip into a fully managed trade idea with a stop-loss and three targets drawn on the chart for you.
Works on all markets (crypto, forex, stocks, indices, commodities) and all timeframes.
🧩 WHY THESE COMPONENTS WORK TOGETHER
A classic supertrend-style trail has three chronic problems. First, its width is fixed — the same multiplier that protects you in chop gives back too much profit in a strong trend. Second, a raw trail flip says nothing about signal quality — a flip in dead, low-volume conditions looks identical to a flip with real participation. Third, a flip is not a trade — you still have to decide where the stop goes, where the targets go, and when to move to break-even.
RTS solves all three with one integrated pipeline:
Baseline MA (6 engines) → Dual volatility measure (ATR + StDev) → RSI momentum engine → Adaptive trail width → Ratcheting trail state machine → HTF bias + volume filters → 0–100 signal score → Wick-anchored SL + TP1/TP2/TP3 → Break-even automation → Trade outcome statistics
The baseline MA defines the anchor the trail hangs from. The volatility engine defines the raw distance. The RSI momentum engine then compresses that distance when momentum is strong — this is what makes the trail "reactive" rather than static. The ratcheting state machine guarantees the trail only ever tightens in the trade's favor (it never backs away from price). The HTF and volume filters decide whether a flip is allowed to become a trade. The scoring engine grades every entry so you can tell an A-setup from a C-setup at a glance. The risk engine converts the signal into concrete levels anchored to real market structure (the signal bar's wick), and the trade engine tracks every touch, break-even move, stop-out and reversal — feeding honest statistics back to the dashboard.
Remove any link and the chain breaks: without momentum adaptation the trail is just another supertrend; without filters every flip fires; without the wick-anchored stop the levels ignore structure; without outcome tracking you never learn how the system actually behaves on your market.
🔍 WHAT MAKES IT ORIGINAL
1️⃣ Momentum-adaptive trail width — the trail breathes with the market.
Instead of a fixed multiplier, RTS computes a momentum distance from the smoothed RSI and uses it to compress the trail:
— momDist = min(|RSI_smoothed − 50| / 50, 1.0) — 0 means dead-center momentum, 1 means extreme
— effectiveMultiplier = TrailMultiplier × (1 − Adaptivity × momDist × 0.4)
— trailOffset = volatility × effectiveMultiplier
With default Trail Multiplier 2.0 and Adaptivity 1.0, the trail runs at full width in neutral conditions and tightens by up to 40% when RSI pushes toward extremes. Set Adaptivity to 0 and you get a classic fixed-width trail; the default 1.0 gives maximum adaptation. RSI length 13 with EMA smoothing 3 keeps the width changes calm instead of jittery.
Why this matters: strong momentum = clean price movement = you can afford a tight trail that protects open profit. Weak momentum = noise = the trail widens automatically so you don't get shaken out.
2️⃣ Dual volatility engine — ATR, StDev, or a stabilized Hybrid.
Trail distance can be measured three ways (Volatility Length default 13):
— ATR: classic bar-range volatility
— StDev: close-to-close dispersion
— Hybrid (default): (ATR + StDev) / 2
ATR reacts to wicks and gaps; StDev reacts to closing dispersion. Averaging them dampens the weakness of each — a single wild wick inflates ATR but barely moves StDev, so the Hybrid stays stable where a pure-ATR trail would suddenly balloon.
3️⃣ Six baseline engines including KAMA and T3 — with a volume-safety fallback.
The trail anchors to a baseline MA selectable from HMA, ALMA (default, length 21), KAMA, T3, VWMA and EMA. KAMA and T3 are computed from their full formulas internally (Kaufman efficiency-ratio smoothing constant sc = (ER × (fast − slow) + slow)², and Tillson's six-stage EMA cascade with a = 0.7). If you pick VWMA on an instrument whose data feed reports no volume (common on some forex feeds), RTS silently falls back to EMA instead of plotting garbage.
4️⃣ Ratcheting trail state machine — the stop never retreats.
In a bull regime the trail is trail = max(previous trail, baseline − offset): it can only rise. In a bear regime it can only fall. A flip requires a full bar close beyond the trail — intrabar wicks through the line do not flip the trend. This one-way ratchet is what makes the line usable as an actual trailing stop rather than a wavy band.
5️⃣ Non-repainting HTF bias filter.
Optional filter: longs only when the higher timeframe (default 240 = 4H) closes above its 50 EMA, shorts only below. The HTF request uses the last closed HTF bar (index with lookahead), so the bias never changes retroactively — what you see in a live chart is what a backtest would have seen.
6️⃣ Signal quality score 0–100 — every entry is graded, not just fired.
Each entry gets a transparent confluence score:
— Momentum component (0–40): min(momDist / 0.6, 1) × 40
— Volume component (0–30): participation vs the 20-bar volume SMA, clamped; fixed 15 when the feed has no volume
— HTF alignment (10 or 30): 30 when the higher timeframe agrees with the trade direction, 10 when it doesn't
The score is shown in the BUY/SELL label tooltip, in the dashboard "Last signal" row, and in every entry alert. A 90-score long (strong momentum, heavy volume, HTF agrees) and a 45-score long are both valid flips — but you instantly know which one deserves full size.
7️⃣ Wick-anchored stop-loss — structure-aware risk, not a blind ATR offset.
Default SL mode anchors the stop to the signal bar's actual wick:
— Long SL = min(low − 0.25 × ATR, close − 0.5 × ATR)
— Short SL = max(high + 0.25 × ATR, close + 0.5 × ATR)
The 0.25 × ATR buffer sits the stop just beyond the wick (where stop-hunts reach), and the 0.5 × ATR minimum distance prevents absurdly tight stops on small-bodied signal bars. A classic fixed ATR mode (SL = entry ± multiplier × ATR, ATR length 14) is available too. Targets are pure R-multiples of the actual risk: TP = entry ± risk × multiplier.
Four one-click risk presets: Conservative (SL 2.5×ATR, TP 1R/2R/4R), Balanced (default: 1.5×ATR, 1R/2R/3R), Aggressive (1.0×ATR, 1.5R/2.5R/4R), Scalping (0.8×ATR, 0.8R/1.5R/2R), plus a fully manual Custom preset with input validation (TP1 < TP2 < TP3 enforced).
8️⃣ Full trade lifecycle engine with honest intrabar rules.
RTS doesn't just draw levels — it tracks the trade like a journal:
— Hits are checked only on confirmed bars, and never on the entry bar itself (entry-bar guard)
— TP-priority model: if a bar touches both a TP and the SL, the TP touch registers first (this optimistic assumption is disclosed right in the dashboard tooltip)
— Break-even automation: once TP1 is touched, the stop moves to entry; a BE moved this bar cannot stop you out on the same bar
— Opposite confirmed signal reverses the position (closes the old trade, opens the new one)
— Win definition is fixed and transparent: a trade counts as a WIN once TP1 has been touched (TP3 close, BE stop-out after TP1, or reversal after TP1); closed before TP1 = loss
9️⃣ Persistent trade visualization.
Entry (subtle dotted), SL (solid, prominent) and TP1/TP2/TP3 (dashed) lines extend with the live trade. When a TP is touched, its line turns solid teal with a ✓ on the label. When break-even activates, the original SL line dims to a record and the entry label is annotated "→ SL (BE)". After the trade closes, the drawing persists as a record until the next entry replaces it — you can scroll back and see exactly how each trade resolved.
🔟 Dashboard 2.0 with period-filtered statistics.
A sectioned panel (Market / Trade / Stats — each toggleable, position and font size configurable):
— Market: trend direction, trend age in bars, HTF bias, smoothed RSI, last signal with score and bars-ago
— Trade: entry, SL (with "BE @" marker), TP1–TP3 with ✓ checkmarks, R:R at TP1, SL distance in % — collapses to one row when flat
— Stats: closed trades, wins, losses, win rate with a ▰▱ gauge, and a "Form" strip of the last 10 results
The win-rate window is selectable: last 24 Hours, last 30 Days, or All-Time — computed from timestamped trade closures kept in a rolling 31-day buffer. Statistics reset on chart reload, and this is disclosed directly in the dashboard tooltips.
📖 HOW IT WORKS — CALCULATION FLOW
Step 1 — Baseline: the selected MA engine (ALMA 21 by default) is computed as the trail anchor.
Step 2 — Volatility: ATR and StDev over 13 bars are combined per the selected engine into one volatility measure.
Step 3 — Momentum: RSI(13) is EMA-smoothed(3); its distance from 50 (normalized 0–1) compresses the trail multiplier by up to 40%.
Step 4 — Trail update: the ratcheting state machine raises the trail in bull regimes / lowers it in bear regimes; a confirmed close through the trail flips the regime.
Step 5 — Filtering: the flip becomes an entry signal only if it passes the optional HTF bias and volume-confirmation filters, on a confirmed bar, after the warm-up period.
Step 6 — Scoring: the entry is graded 0–100 from momentum, volume participation and HTF alignment.
Step 7 — Risk placement: SL is anchored to the signal bar's wick (or fixed ATR), TP1–TP3 are projected as R-multiples of the actual risk per the active preset.
Step 8 — Trade tracking: every confirmed bar is checked for TP touches, break-even activation, stop-out or reversal; outcomes update the win/loss statistics and the Form strip.
📖 HOW TO USE
🎯 Quick start:
1. Add the indicator to your chart. Defaults (ALMA 21, Hybrid volatility, Balanced preset) are ready to use.
2. Wait for a ▲ BUY or ▼ SELL label — hover it to see the score, RSI, SL and TP1.
3. Check the dashboard: score of the last signal, HTF bias, and current R:R.
4. Prefer high-score signals (70+) where the HTF bias agrees with the trade direction.
5. Manage by the drawn levels: partial at TP1 (stop moves to break-even automatically), remainder toward TP2/TP3 or until the trail flips.
👁️ Reading the chart:
— 🟢 Green trail line below price = bull regime; it can only rise
— 🔴 Red trail line above price = bear regime; it can only fall
— ▲ BUY / ▼ SELL labels = filtered, confirmed entries (tooltip shows score and levels)
— Dotted line = entry reference · solid red = stop-loss · dashed green = TP1/TP2/TP3
— Teal solid TP line with ✓ = target reached · dimmed SL + "→ SL (BE)" = stop moved to entry
— Optional: soft trend fill between trail and baseline, and regime-colored candles
📊 Dashboard fields:
— Trend / Age: current regime and bars since the last flip
— HTF Bias: higher-timeframe direction (Off when the filter is disabled)
— RSI: the smoothed momentum value driving trail width
— Last signal: direction · score (bars ago)
— Entry / SL / TP1–TP3 / R:R / SL Dist: full live trade card
— Trades / Wins / Losses / Win rate: statistics for the selected period (24H / 30D / All-Time)
— Form: last 10 results, ▰ = win, ▱ = loss, newest on the right
🔧 Tuning guide:
— Too many flips / whipsaws: raise Trail Multiplier toward 2.5–3.0, raise Baseline Length toward 34–55, or enable the HTF Bias Filter
— Exits feel too late: lower Trail Multiplier toward 1.8, or keep Adaptivity at 1.0 so strong momentum tightens the trail
— Trail width feels jumpy: lower Momentum Adaptivity to 0.4–0.6 or raise Momentum Smoothing to 5–8
— Too few signals: disable the volume filter, or shorten Baseline Length toward 13–21
— Stops too tight on your market: switch the preset to Conservative, or use ATR mode with a higher SL multiplier
— Scalping lower timeframes: Scalping preset + Volatility Length 10 + consider HMA baseline
⚙️ KEY SETTINGS
⚙️ Main:
— Baseline MA Type (default ALMA): trail anchor engine — HMA / ALMA / KAMA / T3 / VWMA / EMA
— Baseline Length (default 21): higher = smoother, fewer flips
— Momentum (RSI) Length (default 13) and Smoothing (default 3): the adaptive-width driver
— Volatility Engine (default Hybrid) and Length (default 13)
— Trail Multiplier (default 2.0): base trail distance in volatility units
— Momentum Adaptivity (default 1.0): 0 = fixed width, 1 = up to 40% tightening
🔍 Filters:
— HTF Bias Filter (default off) + Higher Timeframe (default 240): trade only with the bigger trend
— Volume Confirmation (default off) + Threshold (default 1.2 × SMA20): require real participation; auto-bypassed on no-volume feeds
🛡️ Risk Management:
— Risk Preset (default Balanced): Conservative / Balanced / Aggressive / Scalping / Custom
— SL Mode (default Wick-Anchored): structure-based stop or fixed ATR
— ATR Length (default 14), SL / TP1 / TP2 / TP3 multipliers (Custom preset)
— Break-Even After TP1 (default on)
— SL/TP lines, labels, % distance and per-line styles are all configurable
🎨 Visual:
— Theme Auto / Dark / Light (auto-detects chart background), trail / baseline / fill / labels / candle-coloring toggles, font sizes, bull & bear colors
📊 Dashboard:
— Show/hide the panel and each section, position (4 corners), font size, Win Rate Period (24 Hours / 30 Days / All-Time)
🔔 ALERTS
— 🟢 LONG / 🔴 SHORT — entry with price, SL, TP1–TP3, R:R and score; plain text or JSON webhook payload for bot integration
— 🎯 TP1 HIT / 🎯🎯 TP2 HIT — target touches
— 🏆 TP3 HIT — final target, trade closed
— 🛑 SL HIT / 🛡️ BE STOP-OUT — stop-outs with entry and stop price
— 🛡️ BREAK-EVEN — stop moved to entry after TP1
— 🔄 REVERSAL — opposite signal closed the trade and opened the other direction
— ▲ / ▼ FLIP (optional, informational) — trail flipped but the entry was blocked by filters
All alerts fire once per confirmed bar close. Set up a single alert with "Any alert() function call" and toggle the categories you want in the settings.
⚠️ IMPORTANT NOTES
— 🚫 No repainting. Signals require barstate.isconfirmed; a flip needs a full bar close through the trail; the HTF filter reads only the last closed higher-timeframe bar; all alerts use bar-close frequency. What you see on historical bars is what the live chart produced.
— 📐 Intrabar assumption disclosed. When a single bar touches both a TP and the SL, the TP registers first (optimistic model). This is stated in the dashboard tooltip so the statistics are interpreted correctly.
— 📐 Statistics are session-based. Win/loss counts and the Form strip are computed from the loaded chart history and reset on chart reload. Past performance does not guarantee future results.
— ⚖️ Scope. RTS is a trend-following system — like any trail-based approach it performs best in trending conditions and will flip more often in tight ranges. Use the HTF and volume filters and the score to skip low-quality environments.
— 🛠️ This is an analysis tool, not an automated trading bot. It identifies trend regimes, grades entries, and draws structured risk levels — trade decisions remain yours.
— 🌐 Works on all markets and timeframes. Instruments without volume data are handled automatically (VWMA falls back to EMA, the volume filter bypasses, scoring uses a neutral volume component).
The indicator is completely free. Indicator

Indicator

HalfTrend Long/Short Signal Engine [BigBeluga]HalfTrend Long/Short Signal Engine is an institutional-grade trend tracking toolkit built for PulseWire. 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. Indicator

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. Indicator

Strategy

Indicator

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. Strategy

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. Strategy

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.
Strategy

Strategy

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.
Strategy

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. Indicator

Indicator

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). Indicator
