OPEN-SOURCE SCRIPT
Cập nhật

Synapse Trail Pro [WillyAlgoTrader]

43 912
◆ SYNAPSE TRAIL PRO [WillyAlgoTrader] — FREE & OPEN-SOURCE

Synapse Trail Pro is an overlay indicator that fuses a ratcheted ATR trail, a 3-factor market regime engine, a 5-factor signal quality score, and a complete risk-management layer (SL + TP1/TP2/TP3 + automatic break-even) into one decision-support system. Every signal arrives pre-graded (A / B / C), pre-leveled (SL and three targets drawn on the chart), and pre-contextualized (regime, HTF bias, volume, RSI, ATR percentile — all in one dashboard).

The core problem it solves: classic SuperTrend-style trails fire too many signals in choppy markets, and the trader is left guessing which ones to trust. Synapse Trail Pro keeps the clean visual of an ATR trail but scores each signal 0–100 using multi-factor confluence and tells you the market regime in plain language — so you know at a glance whether the chart wants a trend signal taken or skipped.

This is fully free, open-source Pine v6 — no paywall, no invite, no DM required. Use it, study it, adapt it.


🧩 WHY THESE COMPONENTS WORK TOGETHER

A trail line alone tells you direction. A quality score alone tells you confidence. A regime filter alone tells you environment. None of these are useful in isolation — a high-confidence signal in a choppy regime is still a coin flip, and a clean trail flip in a strong trend with no volume confirmation can still fail.

Synapse Trail Pro fuses them into a single pipeline:

ATR Trail (with optional ratchet) → Direction Flip Detection → Regime Score (ADX + Choppiness + R²) → Quality Score (HTF + Volume + RSI + Regime + Break Strength) → Grade A/B/C → Risk Levels (preset SL + TP1/TP2/TP3) → Break-Even after TP1 → Lifecycle Stats

The trail produces the raw signal. The regime engine tells you whether the market is even capable of trending right now. The quality score weighs five independent confluence factors against that regime. The grade compresses the score into a single letter you can act on. The risk layer then drops your SL, three TPs, and break-even logic onto the chart automatically — so the moment the signal fires, you already see the trade plan.

Without the regime engine, you'd take signals in chop. Without the quality score, you'd treat every flip equally. Without the risk levels, you'd still be calculating SL and TPs manually after the signal. Each component covers a blind spot of the others.


🔍 WHAT MAKES IT ORIGINAL

1️⃣ Ratcheted ATR Trail with Adaptive Volatility Multiplier.

The trail center is an EMA (default 21) of close, with bands at ±ATR × multiplier (default base 1.618 — the golden ratio). When the Ratchet option is on (recommended), the lower band only moves up in a long position and the upper band only moves down in a short — never loosens, only tightens. On a direction flip, the band resets to its raw value.

When the Adaptive Volatility Multiplier is on, the base multiplier auto-scales based on the 100-bar ATR percentile rank:
— Low vol (rank < 30) → multiplier × 0.8 (narrower band, catch the move earlier)
— Mid vol (30–70) → multiplier × 1.0 (default)
— High vol (rank > 70) → multiplier × 1.25 (wider band, avoid noise wicks)

Why this matters: a fixed multiplier overreacts in calm markets and gets whipsawed in volatile ones. Percentile-rank scaling keeps the trail behavior consistent across market conditions.


2️⃣ Composite Market Regime Score (0–100) — three-factor blend.

Each bar, three independent measurements vote on whether the market is trending or choppy:

— ADX (weight 40%): standard Directional Movement ADX, length 14. Score = min(ADX / 50 × 100, 100). High ADX = strong directional pressure.
— Choppiness Index (weight 35%): ChopIdx = 100 × log10(sum(TR, N) / (highest(high, N) − lowest(low, N))) / log10(N), then inverted to a trend score: chopScore = 100 − ChopIdx. Length 14. Low choppiness = clean directional movement.
— R² Linearity (weight 25%): R² = correlation(close, bar_index, 50)². Measures how linearly price is moving. R² near 1 = clean trend, R² near 0 = pure noise.

Final regime score = ADX × 0.40 + chopScore × 0.35 + R² × 100 × 0.25.

Thresholds:
— Score ≥ 60 → Trending (green)
— Score < 35 → Choppy (red) — signals flagged with ⚠ or hard-skipped
— Between → Mixed (yellow)

Why three indicators instead of one: ADX measures strength but lags. Choppiness measures range expansion but can spike on news. R² measures linearity but is noisy on short windows. Combined and weighted, they cover each other's failure modes.


3️⃣ 5-Factor Quality Score (0–100) with letter grading.

When a trail-flip signal fires, it's scored on five confluence factors:

— HTF Bias (max 30 points): higher-timeframe (4× current TF by default) EMA-50 bias. Match = 30, against = 0, HTF data missing or filter off = 15 (neutral credit).
— Volume Confirmation (max 20 points): volume > 20-bar SMA × 1.3 (configurable). Auto-bypassed and given full credit on volume-less instruments (FX).
— RSI Momentum (max 20 points): bullish signal needs RSI > 50, bearish needs RSI < 50.
— Regime Score (max 20 points): regimeScore × 0.20.
— Break Strength (max 10 points): how far past the band close pierced, capped at 3 × ATR. breakStrength = min(|breakDist| / ATR, 3) / 3 × 100, then × 0.10.

Grades:
— Score ≥ 75 → A (high-quality, all factors aligned)
— Score ≥ 55 → B (acceptable, most factors aligned)
— Score < 55 → C (weak — most factors against, consider skipping)

A "Min Quality Score" input lets you hide everything below a threshold (e.g., set to 55 to show only A and B grades).


4️⃣ Risk Presets with Per-Trade Snapshot Locking.

Four risk presets (plus Custom) auto-set SL × ATR and TP1/TP2/TP3 as R-multiples:

— Conservative: SL 2.5 × ATR, TP 1R / 2R / 4R
— Balanced (default): SL 1.5 × ATR, TP 1R / 2R / 3R
— Aggressive: SL 1.0 × ATR, TP 1.5R / 2.5R / 4R
— Scalping: SL 0.8 × ATR, TP 0.8R / 1.5R / 2R
— Custom: full manual control

Critical detail: SL and TP multipliers are snapshotted at entry. If you change the preset mid-trade, the open position keeps its original levels — and the Avg R statistic stays accurate (each closed trade contributes its own-time R values).


5️⃣ Break-Even Logic with Diagnostic BE-Save Counter.

When Break-Even After TP1 is on (recommended), reaching TP1 automatically moves the stop-loss to entry price. From the next bar onward, any wick at entry stops out at break-even instead of original SL — letting winners run risk-free to TP2/TP3.

A dedicated BE Saves counter on the dashboard tracks wins that closed because BE-stop fired (TP1 reached but TP3 didn't). A high BE-save ratio is a diagnostic signal that your TP3 may be too far — consider tightening.


6️⃣ Same-Bar Hit Guard + Realistic Closure Logic.

Two guards prevent unrealistic results:

— Entry-bar hold: SL/TP hits are ignored on the entry bar itself. A hairpin wick can't instantly stop out a fresh position.
— Same-bar SL+TP1: if both SL and TP1 are hit on the same bar, the trade closes as a LOSS (conservative — mirrors realistic broker behavior on a single wick).

Closures are routed through a single classifier function so flip-closures, SL-closures, and TP3-closures are all tallied identically.


7️⃣ Flip Detection + Dedicated Flip Alert.

A "flip" is when an opposite signal fires while a position is still active. The old trade is classified and counted (its TP-reached state determines W/L and R-multiple), THEN the new position opens. A dedicated POSITION FLIP alert fires in addition to the new buy/sell alert, with from-direction, to-direction, prior entry, and new entry — useful for closing managed positions externally.


8️⃣ Unified Dashboard with Three Toggleable Sections.

One positioned table with three sections you can switch on/off individually:

— Trade section: Direction (with grade), SL (with BE marker), TP1/TP2/TP3 (with ✓ on hit), Risk % / R:R with unicode gauge, Bars in Trade.
— Market section: Regime (with 0–100 gauge), HTF bias, Volume status, RSI, ATR | Volatility-rank with adaptive multiplier.
— Statistics section: Total signals + grade breakdown (A:N B:N C:N), Buy/Sell split, Closed trades, W/L, Win rate, Avg R-multiple, BE Saves, Flips.

Dynamic section headers carry live context (e.g., "─── Trade · LONG · 23 bars ───") so the divider itself summarizes state.


9️⃣ Three Trail Visual Schemes for Different Aesthetics.

— Adaptive (Bull/Bear): classic bright green/red — high visibility.
— Premium Indigo (recommended): muted indigo (long) and earth-brown (short) — financial-terminal aesthetic, never competes with green TP lines.
— Monochrome: neutral grey for ultra-minimal charts.

Optional Double Trail Line adds a dashed secondary line offset by a fraction of ATR (configurable 0.05–1.0 × ATR), creating a "channel" visual. The dashed segments are drawn via a ring-buffer of line.new(... line.style_dashed) instead of plot() — this produces TradingView's native dashed look that plot() can't render natively.


🔟 Theme Auto-Detection + Premium Color Palette.

The indicator detects whether your chart background is dark or light (using color.r(chart.bg_color) < 128) and adapts every palette element accordingly. Theme can also be force-set to Dark or Light. Light-theme variants use deeper, more saturated colors to maintain contrast (e.g., deep crimson SL on white, dark amber for BE).

All label text colors are calibrated for ≥4.5:1 contrast against their background (e.g., dark green text on bright green long labels = 7.8:1 ratio).


1️⃣1️⃣ Webhook-Ready JSON Alerts with Full Payload.

Every buy/sell/flip/SL-hit/TP-hit/BE-activation event can fire as plain text OR structured JSON. The JSON payload includes action, ticker, timeframe, price, SL, TP1/TP2/TP3, R:R, grade, quality score, regime, choppy flag, and flip flag — ready for any webhook automation.


🧠 HOW IT WORKS — STEP BY STEP

Step 1 — ATR + Trail Center: ATR(13) and EMA(21) of close are computed. Raw bands = EMA ± ATR × multiplier (base 1.618).

Step 2 — Adaptive Multiplier (optional): If on, the multiplier scales by 100-bar ATR percentile (×0.8 / ×1.0 / ×1.25).

Step 3 — Ratchet Logic (optional): In a long, the lower band can only move up. In a short, the upper band can only move down. On a direction flip, the band resets to raw.

Step 4 — Direction Flip Detection: Close > prev upper band → direction = 1 (long). Close < prev lower band → direction = −1 (short). A change in direction is the raw signal.

Step 5 — Regime Score: ADX × 0.40 + ChopScore × 0.35 + R² × 100 × 0.25. Trending ≥ 60, Choppy < 35.

Step 6 — Quality Score: HTF (0/15/30) + Volume (0 or 20) + RSI (0 or 20) + Regime × 0.20 + BreakStrength × 0.10. Grade A ≥ 75, B ≥ 55, C < 55.

Step 7 — Filtering: Min Quality threshold, choppy-skip toggle, barstate.isconfirmed gating.

Step 8 — Risk Levels: SL = entry ± ATR × slMult. TP1/TP2/TP3 = entry ± slDistance × tpMult. All snapshotted to the trade.

Step 9 — Lifecycle: On TP1 first-touch → BE activates (SL → entry). On SL or TP3 → trade closes, classified by tp1Reached (WIN if true, LOSS if false), R-multiple credited (1/3 per TP partition), state reset.

Step 10 — Visuals + Alerts: SL/TP lines drawn forward, labels updated on hit (✓ + cyan), alerts fired with full payload, dashboard updated.


📖 HOW TO USE — BEGINNER GUIDE

🎯 Quick start (5 steps):
1. Add Synapse Trail Pro to your chart on any timeframe.
2. Open Settings. Leave defaults for the first session — they are tuned for general use (Balanced preset, Premium Indigo trail, HTF filter on, BE on).
3. Wait for the first signal to fire (▲ Long or ▼ Short marker). The marker shows the grade (A/B/C) and a ⚠ flag if in choppy regime.
4. Read the dashboard (top-right by default). Note the Direction, Grade, Regime, and the SL/TP1/TP2/TP3 levels — these are your full trade plan.
5. Execute the trade in your broker using the SL and TPs from the dashboard. Optionally partition position 1/3 at each TP.

👁️ Reading the chart:
— 🟢 ▲ Long Grade-letter below a bar = Buy signal. Color matches grade quality.
— 🔴 ▼ Short Grade-letter above a bar = Sell signal.
— ⚠ next to the grade = signal fired in choppy regime (be cautious or skip).
— Trail line = current direction context. Indigo = long bias, terracotta = short bias (in Premium scheme).
— Dashed secondary line = soft/hard limit zone, offset by a fraction of ATR.
— ENTRY line (dotted blue) = your entry reference price.
— SL line (solid red) = your stop-loss.
— TP1 / TP2 / TP3 lines (dashed green) = your take-profit targets. Turn solid teal with ✓ on hit.
— Entry → SL (BE) label in amber = break-even is active (TP1 was reached, SL is now at entry).

📊 Dashboard fields (Trade section):
— Direction: LONG / SHORT / FLAT + Grade letter.
— SL: stop-loss price. Shows "BE @" prefix when break-even is active.
— TP1 / TP2 / TP3: target prices. ✓ prefix once reached.
— Risk / R:R: distance % from entry to SL + current R:R + visual gauge.
— Bars in Trade: how many bars since entry.

📊 Dashboard fields (Market section):
— Regime: Trending / Mixed / Choppy + 0–100 gauge.
— HTF: higher-timeframe bias (Bullish / Bearish / Flat / off).
— Volume: Confirmed / Weak / no data / off.
— RSI: current 14-period RSI value, color-coded.
— ATR | Vol: ATR value, 100-bar volatility percentile, and current adaptive multiplier.

📊 Dashboard fields (Statistics section):
— Signals: total fired + breakdown (A:N B:N C:N).
— Buy / Sell: directional split.
— Closed: total wins + losses (flip, SL, and TP3 closures all counted).
— W / L: wins / losses.
— Win Rate: TP1-reached = WIN. Color-coded ≥ 55% green, ≥ 45% yellow, else red.
— Avg R: average realized R-multiple per closed trade.
— BE Saves: wins that closed because BE-stop fired (diagnostic).
— Flips: trades closed by opposite signal mid-position.

💡 Beginner trading workflow:
1. Start with the Balanced preset and HTF Bias Filter ON.
2. Only take A-grade or B-grade signals — set Min Quality Score to 55.
3. Skip every signal flagged with ⚠ (choppy regime) until you understand the regime engine — or enable Hard-skip Choppy.
4. Use the Premium Indigo trail scheme — the muted colors keep your focus on the SL/TP levels, not the trail itself.
5. Always partition position 1/3 at each TP — that's what the R-multiple math assumes.
6. After 30–50 trades, review the Statistics section: if Avg R is positive, the setup works. If BE Saves > 30% of wins, consider tightening TP3.

🔧 Tuning guide:
— Too many signals: increase Min Quality Score to 75 (A-grade only), enable Hard-skip Choppy.
— Too few signals: lower Min Quality to 0, turn off HTF filter, switch from Balanced to Aggressive preset.
— Stops too tight: switch to Conservative preset (SL 2.5 × ATR).
— Stops too wide: switch to Scalping preset (SL 0.8 × ATR).
— BE stopping you out too often: disable Break-Even After TP1.
— Trail too jumpy: increase Trail EMA Length from 21 to 34, enable Ratchet.
— Trail too sluggish: decrease Trail EMA Length to 13, decrease ATR Length to 8.
— Chart too busy: turn off Double Trail Line and Regime Background, set Trail History Bars to 50.


⚙️ KEY SETTINGS REFERENCE

⚙️ Main Settings:
— ATR Length (default 13): ATR period for volatility band.
— Base ATR Multiplier (default 1.618 — golden ratio): base band width.
— Trail EMA Length (default 21): EMA period for trail center.
— Adaptive Volatility Multiplier (default off): auto-scale multiplier by 100-bar ATR percentile.
— Ratchet Trail (default on): trail only tightens in position direction.

🔍 Signal Filters:
— Min Quality Score (default 0): hide signals below threshold (0 = all, 55 = B+, 75 = A only).
— Hard-skip Choppy Signals (default off): fully suppress signals in choppy regime.
— Use HTF Bias Filter (default on): Quality Score bonus for HTF-aligned signals.
— HTF for Bias (default empty = auto 4×): higher timeframe for bias check.
— Use Volume Confirmation (default off): bonus when volume > 20-SMA × threshold.
— Volume Threshold (default 1.3): volume × SMA20 to count as confirmation.

🌊 Market Regime:
— ADX Length (default 14)
— Choppiness Length (default 14)
— R² Regression Length (default 50)

🛡️ Risk Management:
— Risk Preset (default Balanced): Conservative / Balanced / Aggressive / Scalping / Custom.
— Custom SL × ATR (default 1.5)
— Custom TP1/TP2/TP3 × Risk (default 1.0 / 2.0 / 3.0)
— Break-Even After TP1 (default on): move SL to entry on TP1.
— Show SL/TP Lines / Labels / % Distance: all on by default.
— Entry / SL / TP Line Styles: Dotted / Solid / Dashed defaults.

🎨 Visual:
— Theme (default Auto)
— Trail Color Scheme (default Adaptive Bull/Bear) — try Premium Indigo for a financial-terminal look.
— Trail Line Width (default 2)
— Trail History Bars (default 0 = all)
— Double Trail Line (default on)
— Double Trail Offset × ATR (default 0.25)
— Show Buy/Sell Labels / Grade / Regime Background / Watermark

📊 Dashboard:
— Show Dashboard (default on) — master toggle
— Position (default Top Right) — 6 positions available
— Trade / Market / Statistics Section toggles

🔔 Alerts:
— Webhook JSON Format (default off): plain text or structured JSON.
— Alert on TP Hits (default off)
— Alert on SL Hit (default on)
— Alert on Position Flip (default on)


🔔 ALERTS

— 🟢 BUY — ticker, TF, price, SL, TP1/TP2/TP3, R:R, grade, quality score, regime, choppy flag, flip flag
— 🔴 SELL — same payload
— 🔄 POSITION FLIP — from-direction, to-direction, prior entry, new entry
— 🛑 SL HIT — entry, SL price, time
— 🛡️ BE STOP-OUT — fires instead of regular SL when break-even was active
— 🎯 TP1 / TP2 / TP3 HIT — first-touch only, no duplicate fires
— 🛡️ BREAK-EVEN — fires the bar TP1 is reached and SL moves to entry

All alerts support plain text and JSON webhook format. All fire bar-close confirmed (alert.freq_once_per_bar_close).


⚠️ IMPORTANT NOTES

— 🚫 No repainting. All signals require barstate.isconfirmed. Alerts fire once per bar close. The HTF security() call uses the canonical non-repaint pattern (close[1] + ema[1] with lookahead_on), reading the closed HTF bar without future leakage.
— 📐 The trail flip is the raw signal source; quality score and filters only suppress, never invent signals. Same-bar SL+TP1 always resolves as a LOSS (conservative bias toward stop).
— 📐 Statistics counters are session-scoped — they reset on script reload, input change, or by incrementing the "Reset Stats Counter" input. The Stats section is descriptive, not predictive: past behavior on a chart does not guarantee future behavior on the same chart.
— ⚖️ Win = TP1 reached (regardless of how the trade ultimately closed). Avg R assumes 1/3 position partitioned at each TP. These are conventions; your live execution may differ.
— 🛠️ This is an analysis tool, not an automated trading bot. It detects trail flips, scores quality, projects SL/TP zones, and tracks outcomes — trade decisions and execution remain yours.
— 🌐 Works on all markets and timeframes. Volume-based filters auto-bypass on instruments without volume data (FX). Adaptive multiplier and regime engine scale naturally across symbols.
— 📜 Fully open-source Pine v6. Read the code, fork it, adapt it. Feedback and forks welcome.
Phát hành các Ghi chú
Synapse Trail Pro [WillyAlgoTrader] — Update v1.4.0

🔵 OVERVIEW
An EMA- and ATR-based trend indicator with entry-condition scoring, stop-loss and take-profit levels, and context from nearby price levels. Version 1.4.0 refines the interface, alerts, and visual presentation to align with the internal WillyAlgoTrader standard.

🔵 KEY FEATURES
• ATR trail with an optional ratchet that prevents the active boundary from loosening.
• Market regime analysis using ADX, Choppiness, and R².
• A/B/C signal grades, higher-timeframe (HTF) bias, and an optional mandatory HTF alignment filter.
• Distance to the previous daily high/low and the latest confirmed swing levels, expressed in R.
• Adjustable filters for candle range and distance from the EMA.
• A stop-loss, three targets, break-even (BE), and candle-based simulated statistics with configurable trading costs.

🔵 HOW IT WORKS
Direction is determined by price crossing an ATR boundary around the EMA. Entries must satisfy the selected conditions at bar close. Higher-timeframe data comes from completed bars; swing levels become available only after confirmation. Initial risk and target levels are recorded at entry.

🔵 HOW TO USE
First assess the direction, market regime, and distance to the nearest potential obstacle. Room at entry preserves the entry context; Before TP1 warns when a known level is closer than the first target. Compare the new filters one at a time using the same historical data and trading costs.

🔵 SETTINGS
• ATR 13, Trail EMA 21, and a base multiplier of 1.618 are starting settings, not a claim of optimal performance.
• Swing detection defaults to 3 bars on the left and 3 confirmation bars on the right.
• Late-entry filters default to OFF. Starting thresholds are 2.5 ATR for candle range and 2 ATR for distance from the EMA.
• Auto/Dark/Light themes are available. Dashboard sections, lines, labels, and the watermark can be hidden.
• Settings include explanatory tooltips. The score is a heuristic assessment, not the probability of a profitable trade.

🔵 RISK MANAGEMENT
The Balanced preset uses a 1.5 ATR stop and targets at 1R/2R/3R. Conservative, Aggressive, Scalping, and Custom presets are also available. The candle-based model allocates one third of the position to each target; any remaining portion exits at the stop or on a reversal. BE takes effect from the bar after TP1 is reached. Commission and exit slippage default to 0; enter values appropriate to your trading conditions. SL distance % measures the price distance to the stop, not the percentage of account equity at risk.

🔵 ALERTS
Enable Alerts controls all notifications. Use the indicator's alert() events when creating an alert; separate switches control TP, SL, and flip notifications. Text messages include the event type, symbol, timeframe, price, SL/TP levels, R:R, and time. JSON uses stp.events.v1: events for the previous position precede any new entry in the events array. The rr field has been added since version 1.4; handlers with strict schema validation must allow it. This format is incompatible with the original single-action format in version 1.2.

🔵 SUPPORTED MARKETS
The algorithm uses OHLC data and optional volume. Execution across different markets was not tested during this review; universal compatibility is not claimed. Use standard time-based candles rather than synthetic prices.

🔵 TIMEFRAMES
When used, the HTF must be higher than the chart timeframe. Automatic selection is approximately 4× the chart timeframe. Previous daily high/low levels are available on intraday and 1D charts. An optimal timeframe has not been established through market testing.

⚠️ LIVE DATA & LIMITATIONS
BUY/SELL signals and simulated trade events are confirmed at bar close. The trail and rows marked live may change while the current bar is open. The absence of a known level does not imply a clear path to the target. Statistics are recalculated over the loaded historical data; they do not represent actual broker executions or a full Strategy Tester backtest. An advantage from the filters or an increase in profitability has not been demonstrated.

⚠️ DISCLAIMER
This indicator is for educational purposes only. It does not constitute financial advice. Past performance does not guarantee future results. Always use proper risk management.

Tags: Trend Analysis, ATR, Moving Averages, Support and Resistance, Risk Management.

Thông báo miễn trừ trách nhiệm

Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.