PROTECTED SOURCE SCRIPT

Pivot SuperTrend Auto-Opt + WFO + MultiObj + Filter/Diag

163
# Pivot SuperTrend (NetProfit Auto-Optimization) — Summary & Quick Start

## What this strategy is
A self-optimizing **SuperTrend-style** strategy for TradingView Pine v6 that:
- builds a **walk-forward, net-profit optimizer** directly on the chart,
- adapts its trailing stop/entry logic to **market regime** and **volatility**, and
- exposes a **filter/gate suite** so you can dial aggressiveness vs. noise without breaking auto-optimization.

Default tuning: **Bybit ETHUSDT Perpetual, 30m** (works elsewhere once tuned).

---

## Core logic (high level)

### 1) SuperTrend backbone (with Center/Pivots)
- **Center line**: smoothed running pivot from `ta.pivothigh/low`.
- **SuperTrend bands**: `Center ± Factor × ATR(length)` with a carry rule to reduce whipsaws.
- **Trend state**: `+1` above band, `-1` below band.
- **Flip**: trend change; can require **1-bar confirmation**.

### 2) Adaptive smoothing (AMA of ST)
- Performance-weighted **alpha** smooths the trailing stop.
- Alpha clamped to `alpha_min…alpha_max` using optimizer’s fitness.

### 3) On-chart net-profit optimizer (walk-forward)
- Grid of parameters:
- ATR Length `len` (min…max…step)
- ATR Factor `F` (min…max…step)
- Performance memory `A` (min…max…step)
- Each grid point is paper-traded **each bar** including fees/slippage → **fitness = net profit EMA**.
- Every `opt_interval` bars the **best** candidate is activated (with hysteresis).
- Optional: apply only **ATR margin** gate inside the optimizer for speed/stability.

### 4) Regime detection & anti-chop
- Custom **ADX** + **Center slope** to classify **trend** vs **range**.
- Adaptive thresholds in range regime (distance-to-center, ST-near-center block, etc.).
- Optional **ATR fast/slow ratio** gate.
- Other tools: **min bars since flip**, **hold bars after flip**, **distance to center**, **ST near center** block.

### 5) Entry logic
- **Immediate on flip** or **1-bar confirm**.
- Must pass the **Filter Suite** (toggleable gates):
- ATR-margin cross (hard cross or wick reject)
- Trend Regime (require trend)
- Hold-after-flip
- Distance-to-center
- ST-near-center block
- Volatility ratio (ATR fast/slow)
- Min bars since flip (flip cooldown)
- Daily trade cap & post-loss cooldown
- Trading session window

### 6) Starter preset (failsafe)
- Lenient defaults so trades start quickly to build warm-up data; then you can tighten gates.

### 7) Position management
- Strategy entries for “LONG” / “SHORT”.
- Optional **50% take-profit on Center** (“usecenter”).
- **Only-Long** mode supported with separate exit logic if regime turns bearish.

### 8) Risk controls
- **Max trades per day**, **cooldown bars after loss**, **session window**.
- Optional **bar coloring**, **trend shading**, **signal markers**.
- **Diagnostics** labels show which gate blocked an entry (letters `M T H D N V F C CD S`).

### 9) Alerts & Bybit webhook
- Use alert condition: **Any alert() function call**.
- Fires `"LONG_CONFIRMED"` / `"SHORT_CONFIRMED"`.

---

## Inputs overview

- **Pivot / Center**: pivot length; show pivots & center.
- **Visual**: line widths, bar colors, shading; warm-up bars.
- **Execution / Costs**: fee (bps), slippage (bps), “Only long”, 50% center-close.
- **Auto-Optimize**: grids for `len`, `F`, `A`, interval, memory, acceptance floor.
- **Signal Controls**: 1-bar confirm, ATR margin, min bars since flip.
- **Anti-Chop**: distance to center, hold bars, slope len, ST-near-center ATR, ATR slow len & ratio.
- **Trend Regime**: ADX len/threshold, center slope threshold, “require trend”.
- **Risk Gates**: max trades/day, loss cooldown bars.
- **Session**: optional 07:00–22:00 UTC filter.
- **Diagnostics**: show gate diagnostics labels.
- **Filter Suite**: toggle each gate; optional “apply margin to optimizer”.
- **Starter preset** selector.

---

## Plots & UI
- **Adaptive SuperTrend** (active candidate),
- **PP Center** (optional),
- **Trend shading** (price vs ST zone),
- **Entry/Exit markers** (triangles),
- **Diagnostics** text labels (optional).

---

## Webhook notes (Bybit v5)

If you use a direct Bybit webhook:

- **Symbol**: TradingView may emit `ETHUSDT.P`. Bybit wants `ETHUSDT`. Your relay should **strip `.P`**.
- **Side**: TV provides `buy/sell`. Bybit expects `Buy/Sell` → normalize casing in the relay.
- **Reduce-only**: mark exits and partial closes reduce-only to avoid reversals in Hedge mode.
- **Market orders**: pass `"orderType":"Market"`; ignore price or set to `"marketPrice"` if your relay requires it.

**Entry (Market)**
```json
{
"exchange": "BYBIT",
"category": "linear",
"symbol": "{{ticker}}",
"side": "{{strategy.order.action}}",
"orderType": "Market",
"qty": "{{strategy.order.contracts}}",
"reduceOnly": false,
"timestamp": "{{timenow}}",
"clientOrderId": "pst_{{strategy.order.id}}_{{timenow}}"
}

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.