OPEN-SOURCE SCRIPT
تم تحديثه

SuperTrend Optimizer Remastered[CHE]

237
SuperTrend Optimizer Remastered [CHE] — Grid-ranked SuperTrend with additive or multiplicative scoring

Summary

This indicator evaluates a fixed grid of one hundred and two SuperTrend parameter pairs and ranks them by a simple flip-to-flip return model. It auto-selects the currently best-scoring combination and renders its SuperTrend in real time, with optional gradient coloring for faster visual parsing. The original concept is by KioseffTrading Thanks a lot for it.

SuperTrend Optimizer


For years I wanted to shorten the roughly two thousand three hundred seventy-one lines; I have now reduced the core to about three hundred eighty lines without triggering script errors. The simplification is generalizable to other indicators. A multiplicative return mode was added alongside the existing additive aggregation, enabling different rankings and often more realistic compounding behavior.

Motivation: Why this design?

SuperTrend is sensitive to its factor and period. Picking a single pair statically can underperform across regimes. This design sweeps a compact parameter grid around user-defined lower bounds, measures flip-to-flip outcomes, and promotes the combination with the strongest cumulative return. The approach keeps the visual footprint familiar while removing manual trial-and-error. The multiplicative mode captures compounding effects; the additive mode remains available for linear aggregation.

Originally (by KioseffTrading)

Very long script (~2,371 lines), monolithic structure.
SuperTrend optimization with additive (cumulative percentage-sum) scoring only.
Heavier use of repetitive code; limited modularity and fewer UI conveniences.
No explicit multiplicative compounding option; rankings did not reflect sequence-sensitive equity growth.


Now (remastered by CHE)

Compact core (~380 lines) with the same functional intent, no compile errors.
Adds multiplicative (compounding) scoring alongside additive, changing rankings to reflect real equity paths and penalize drawdown sequences.
Fixed 34×3 grid sweep, live ranking, gradient-based bar/wick/line visuals, top-table display, and an optional override plot.
Cleaner arrays/state handling, last-bar table updates, and reusable simplification pattern that can be applied to other indicators.



What’s different vs. standard approaches?

Baseline: A single SuperTrend with hand-picked inputs.
Architecture differences:

Fixed grid of thirty-four factor offsets across three ATR offsets.
Per-combination flip-to-flip backtest with additive or multiplicative aggregation.
Live ranking with optional “Best” or “Worst” table output.
Gradient bar, wick, and line coloring driven by consecutive trend counts.
Optional override plot to force a specific SuperTrend independent of ranking.
Practical effect: Charts show the currently best-scoring SuperTrend, not a static choice, plus an on-chart table of top performers for transparency.

How it works (technical)

For each parameter pair, the script computes SuperTrend value and direction. It monitors direction transitions and treats a change from up to down as a long entry and the reverse as an exit, measuring the move between entry and exit using close prices. Results are aggregated per pair either by summing percentage changes or by compounding return factors and then converting to percent for comparison. On the last bar, open trades are included as unrealized contributions to ranking. The best combination’s line is plotted, with separate styling for up and down regimes. Consecutive regime counts are normalized within a rolling window and mapped to gradients for bars, wicks, and lines. A two-column table reports the best or worst performers, with an optional row describing the parameter sweep.

Parameter Guide

Factor (Lower Bound) — Starting SuperTrend factor; the grid adds offsets between zero and three point three. Default three point zero. Higher raises distance to price and reduces flips.
ATR Period (Lower Bound) — Starting ATR length; the grid adds zero, one, and two. Default ten. Longer reduces noise at the cost of responsiveness.
Best vs Worst — Ranks by top or bottom cumulative return. Default Best. Use Worst for stress tests.
Calculation Mode — Additive sums percents; Multiplicative compounds returns. Multiplicative is closer to equity growth and can change the leaderboard.
Show in Table — “Top Three” or “All”. Fewer rows keep charts clean.
Show “Parameters Tested” Label — Displays the effective sweep ranges for auditability.
Plot Override SuperTrend — If enabled, the override factor and ATR are plotted instead of the ranked winner.
Override Factor / ATR Period — Values used when override is on.
Light Mode (for Table) — Adjusts table colors for bright charts.
Gradient/Coloring controls — Toggles for gradient bars and wick coloring, window length for normalization, gamma for contrast, and transparency settings. Use these to emphasize or tone down visual intensity.
Table Position and Text Size — Places the table and sets typography.

Reading & Interpretation

The auto SuperTrend plots one line for up regimes and one for down regimes. Color intensity reflects consecutive trend persistence within the chosen window. A small square at the bottom encodes the same gradient as a compact status channel. Optional wick coloring uses the same gradient for maximum contrast. The performance table lists parameter pairs and their cumulative return under the chosen aggregation; positive values are tinted with the up color, negative with the down color. “Long” labels mark flips that open a long in the simplified model.

Practical Workflows & Combinations

Trend following: Use the auto line as your primary bias. Enter on flips aligned with structure such as higher highs and higher lows. Filter with higher-timeframe trend or volatility contraction.
Exits/Stops: Consider conservative exits when color intensity fades or when the opposite line is approached. Aggressive traders can trail near the plotted line.
Override mode: When you want stability across instruments, enable override and standardize factor and ATR; keep the table visible for sanity checks.
Multi-asset/Multi-TF: Defaults travel well on liquid instruments and intraday to daily timeframes. Heavier assets may prefer larger lower bounds or multiplicative mode.

Behavior, Constraints & Performance

Repaint/confirmation: Signals are based on SuperTrend direction; confirmation is best assessed on closed bars to avoid mid-bar oscillation. No higher-timeframe requests are used.
Resources: One hundred and two SuperTrend evaluations per bar, arrays for state, and a last-bar table render. This is efficient for the grid size but avoid stacking many instances.
Known limits: The flip model ignores costs, slippage, and short exposure. Rapid whipsaws can degrade both aggregation modes. Gradients are cosmetic and do not change logic.

Sensible Defaults & Quick Tuning

Start with the provided lower bounds and “Top Three” table.

Too many flips → raise the lower bound factor or period.
Too sluggish → lower the bounds or switch to additive mode.
Rankings feel unstable → prefer multiplicative mode and extend the normalization window.
Visuals too strong → increase gradient transparency or disable wick coloring.

What this indicator is—and isn’t

This is a parameter-sweep and visualization layer for SuperTrend selection. It is not a complete trading system, not predictive, and does not include position sizing, transaction costs, or risk management. Combine with market structure, higher-timeframe context, and explicit risk controls.

Attribution and refactor note: The original work is by KioseffTrading. The script has been refactored from approximately two thousand three hundred seventy-one lines to about three hundred eighty core lines, retaining behavior without compiler errors. The general simplification pattern is reusable for other indicators.

Metadata

Name/Tag: SuperTrend Optimizer Remastered [CHE]
Pine version: v6
Overlay or separate pane: true (overlay)
Core idea/principle: Grid-based SuperTrend selection by cumulative flip returns with additive or multiplicative aggregation.
Primary outputs/signals: Auto-selected SuperTrend up and down lines, optional override lines, gradient bar and wick colors, “Long” labels, performance table.
Inputs with defaults: See Parameter Guide above.
Metrics/functions used: SuperTrend, ATR, arrays, barstate checks, windowed normalization, gamma-based contrast adjustment, table API, gradient utilities.
Special techniques: Fixed grid sweep, compounding vs linear aggregation, last-bar UI updates, gradient encoding of persistence.
Performance/constraints: One hundred and two SuperTrend calls, arrays of length one hundred and two, label budget, last-bar table updates, no higher-timeframe requests.
Recommended use-cases/workflows: Trend bias selection, quick parameter audits, override standardization across assets.
Compatibility/assets/timeframes: Standard OHLC charts across intraday to daily; liquid instruments recommended.
Limitations/risks: Costs and slippage omitted; mid-bar instability possible; not suitable for synthetic chart types.
Debug/diagnostics: Ranking table, optional tested-range label; internal counters for consecutive trends.

Disclaimer

The content provided, including all code and materials, is strictly for educational and informational purposes only. It is not intended as, and should not be interpreted as, financial advice, a recommendation to buy or sell any financial instrument, or an offer of any financial product or service. All strategies, tools, and examples discussed are provided for illustrative purposes to demonstrate coding techniques and the functionality of Pine Script within a trading context.

Any results from strategies or tools provided are hypothetical, and past performance is not indicative of future results. Trading and investing involve high risk, including the potential loss of principal, and may not be suitable for all individuals. Before making any trading decisions, please consult with a qualified financial professional to understand the risks involved.

By using this script, you acknowledge and agree that any trading decisions are made solely at your discretion and risk.

Do not use this indicator on Heikin-Ashi, Renko, Kagi, Point-and-Figure, or Range charts, as these chart types can produce unrealistic results for signal markers and alerts.

Best regards and happy trading

Chervolino
ملاحظات الأخبار
Some adds
ملاحظات الأخبار
Differences vs. the original (KioseffTrading)

Scope and architecture: This version collapses the large procedural script into a compact, modular structure. It replaces ad-hoc logic with a fixed, transparent grid of SuperTrend pairs and a per-pair flip-based return tracker.

Selection logic: Instead of a single, static parameter choice, it ranks one hundred and two combinations on the chart and auto-plots the current leader.

Evaluation modes: Adds a Multiplicative aggregation mode next to Additive and makes it the default.

UI and diagnostics: On-chart ranking table, gradient bar/wick encoding for trend persistence, and an optional override plot for controlled testing.

Refactor outcome: Similar visual intent, but a different mechanism for selection, evaluation, and presentation. It is a streamlined optimizer rather than a monolithic indicator.

Why “Multiplicative” is the better default (plain English, no math)

Matches how capital grows: Real trading equity compounds. The multiplicative mode mirrors that behavior by chaining gains and losses in the same way an account balance evolves over time.

Correct weighting of path and drawdowns: A large loss requires a proportionally larger recovery. Multiplicative aggregation respects this asymmetry, so sequences with deep dips are penalized appropriately.

Fair comparison across parameter sets: Two settings with the same average move can have very different equity paths. Multiplicative scoring highlights the one with smoother compounding rather than just a high sum of isolated percentages.

Robust to flip frequency: Additive sums can be inflated by many small trades. Multiplicative aggregation reduces this bias by focusing on the compounded effect of the sequence, not the raw count of flips.

Practical takeaway: When you care about realistic account behavior and stable rankings across regimes, multiplicative is the safer baseline. Additive remains useful for quick, linear diagnostics or when you explicitly want to ignore compounding effects.

إخلاء المسؤولية

لا يُقصد بالمعلومات والمنشورات أن تكون، أو تشكل، أي نصيحة مالية أو استثمارية أو تجارية أو أنواع أخرى من النصائح أو التوصيات المقدمة أو المعتمدة من TradingView. اقرأ المزيد في شروط الاستخدام.