OPEN-SOURCE SCRIPT
Updated

Stop Loss Optimizer Engine [AGPro Series]

1 442
Stop Loss Optimizer Engine [AGPro Series]

🔹 OVERVIEW

Stop Loss Optimizer Engine compares four independent stop-loss methodologies side by side on a single chart, so traders can see at a glance where each approach would place protection and which one has historically held up best on the current symbol and timeframe. Every method is calculated for both LONG and SHORT, giving eight reference levels plus a compact panel with distance-to-price and a historical hold-rate statistic per method. A Risk Zone highlights the area between current price and the method with the strongest historical hold-rate, providing a clean S/R-style visual anchor for position sizing and R-multiple planning.

🔹 UNIQUE EDGE

Most stop-loss indicators on the platform commit to a single philosophy — pure ATR, pure Chandelier, or pure structure. Traders who want to compare approaches end up loading multiple scripts and eyeballing the differences. Stop Loss Optimizer Engine is built around a different premise: volatility, structure, trailing and recent-extreme stops each have environments in which they work well, and the trader should decide based on evidence rather than habit. The indicator renders all four on one chart, adds a per-method hold-rate measured on the active instrument, and flags the highest-hold-rate method with a star marker so the comparison is always a single glance away. The Risk Zone is drawn using the current-best method, which means the visual anchor adapts to whichever approach is statistically holding up best on that symbol and timeframe right now.

🔹 METHODOLOGY

The four engines are independent and each produces a LONG and a SHORT level:

ATR-SL — close minus or plus ATR × multiplier. Volatility-adaptive, widens in turbulent markets, tightens in calm ones.

Pivot-SL — the most recent confirmed pivot low or pivot high. Respects market structure, places the stop beyond the last reversal point rather than at an arithmetic distance.

Chandelier-SL — highest high minus ATR × multiplier for LONG, lowest low plus ATR × multiplier for SHORT. The classic Le Beau / Elder trailing stop, designed to follow strong trends without premature exits.

Swing-SL — the lowest low or highest high over a short lookback. A simple, robust baseline that works well for shorter trades and scalping.

Hold Rate — for every historical bar in the lookback window, the indicator records the SL level that each method would have produced at that bar, then checks whether price breached that level within a fixed forward window. Hold Rate is the percentage of evaluated bars in which the SL was not breached. This is a pure historical observation, not a forward performance projection.

🔹 SIGNALS & ALERTS

Visual — dotted lines for LONG stops (plotted below price), dashed lines for SHORT stops (plotted above price). Each method uses a distinct color. Labels sit at the right edge of each line with the method name and exact price. A dedicated anti-overlap resolver repositions labels vertically whenever two or more methods produce near-identical levels, so the rightmost chart panel stays readable in tight clusters.

Risk Zone — a shaded rectangle between current close and the highest-hold-rate SL on the trend-dominant side, extending forward from the current bar. Color matches the selected best method.

Panel — four-column layout showing method, LONG price (and distance %), SHORT price (and distance %), and Hold Rate, with a star marker beside the method currently holding the highest rate. A trend footer reports Bullish or Bearish based on the EMA50 filter.

Alerts — four pre-configured conditions for price breaching the ATR and Chandelier SL levels on either side.

🔹 KEY INPUTS

Method toggles for each of the four engines. Length and multiplier inputs per method, with balanced defaults (ATR 1.5× / 14, Pivot length 5, Chandelier 2.5× / 22, Swing lookback 7). Hold-rate statistics lookback and forward window, defaulting to 1000 and 10 bars. Visual controls for long-side lines, short-side lines, labels, the Risk Zone and a trend-based dimming of the counter-trend side. Panel location (six positions), panel theme (Dark or Light), and adjustable font sizes for panel and labels, all defaulting to Normal.

🔹 HOW TO USE

Open the indicator on any symbol and any timeframe. Read the panel first — the starred method is the one with the best historical hold-rate on the current chart. Pick a method that matches the trade plan: ATR for volatility-aware scalps, Pivot for structural setups, Chandelier for trend-following swings, Swing for simple quick trades. Use the Hold Rate column as secondary evidence, not as a standalone forecast. Read the SL price and the distance percentage next to it to size position accordingly — a 2% stop and a 6% stop are not the same trade, even on the same entry. The Risk Zone is a convenience visual for the trend-dominant side and should be interpreted together with the other levels, not in isolation.

🔹 LIMITATIONS & TRANSPARENCY

Hold Rate is a backward-looking statistic computed on historical bars of the active chart. It describes what would have happened under a fixed forward-window assumption on past data and does not guarantee any future behavior. The forward-window length, lookback size and method parameters all influence the resulting numbers; changing inputs changes the statistic. The Pivot-SL method depends on the availability of confirmed pivots in the lookback window and will fall back to a conservative ATR-based placeholder when a pivot is not yet confirmed. Risk Zone selection is based on hold-rate ranking, which can switch between methods as markets evolve. This script is a decision-support tool for discretionary risk management, not a trade-entry signal generator. Always combine with independent analysis and sound position sizing. Past performance of any stop-loss method does not guarantee future results.

🔒 RISK DISCLOSURE

This script is provided for educational and informational purposes only. It is not financial, investment or trading advice. Trading involves substantial risk of loss; use at your own discretion and risk.
Release Notes
UPDATE NOTES - v1.1

This update focuses on measurement accuracy and honest statistics.

The core purpose of the script remains unchanged.
This release improves how stop-loss levels are validated, how hold-rate
statistics are sampled, and how the comparison is presented on the panel.

This script continues to function as an analytical and visualization tool.
It does not attempt to predict price direction or provide guaranteed outcomes.


------------------------
What Changed
------------------------

- Side-validity gating was introduced across the whole script. A long
stop is only meaningful below current price and a short stop only above
it. Trailing formulas (Chandelier in particular) can land on the wrong
side after sharp moves; such levels are no longer drawn on the chart,
appear as a neutral dash in the panel, and are excluded from statistics.
Previously a wrong-side level was displayed as if it were a placeable
stop and counted as an instant hit, which unfairly depressed that
method's hold rate.

- Hold-rate statistics are now validity-gated and reported with their
sample size. Every rate in the panel shows the number of valid
historical placements behind it (for example 57.0% n=940). Early bars
where the offset level is not yet defined are excluded as well, so the
rate is never inflated by undefined history.

- The combined hold rate per method is now weighted by each side's
valid sample size instead of a simple average, so a side with very few
valid placements cannot distort the method's overall figure.

- Breach alerts were added for Pivot-SL and Swing-SL on both sides.
All four methods now have complete long and short alert coverage.

- Internal declarations were normalized to one per line for stricter
Pine v6 compliance and easier maintenance.


------------------------
Visual Improvements
------------------------

- The best-method row is now highlighted with a subtle accent
background and a simple text marker, replacing the previous emoji
star for a cleaner, more professional panel surface.

- Wrong-side levels no longer appear among the opposite side's labels,
which removes a confusing artifact where a long stop could be printed
above price inside the short-label stack.

- All panel and label text now uses plain characters for consistent
rendering across platforms and themes.


------------------------
Interface & Usability
------------------------

- The Hold Rate column header carries a tooltip explaining exactly how
the statistic is sampled.

- Default visual settings, label density, line styles, and the
anti-overlap label resolver behave as before.


------------------------
Behavior Notes
------------------------

This update does not change how any stop-loss level is calculated.
ATR-SL, Pivot-SL, Chandelier-SL, and Swing-SL formulas are untouched.

The goal is to make the comparison honest and verifiable, not to
introduce new predictive behavior.

Hold rates may shift slightly compared to the previous version because
invalid placements are no longer part of the sample. The new figures
are the more accurate ones.


------------------------
Limitations Reminder
------------------------

The script remains a rule-based analytical tool.

Hold rates are measured on the current chart and timeframe only. They
describe how each method behaved historically under this configuration;
they do not guarantee future behavior.

Market conditions such as volatility, liquidity, and timeframe
differences may affect how levels and statistics appear.


------------------------
Risk Reminder
------------------------

This script is for educational and analytical purposes only.

It does not provide financial advice or guaranteed trading outcomes.

Users remain responsible for their own decisions.

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.