OPEN-SOURCE SCRIPT
已更新 🏛️ INSTITUTIONAL TRENDLINE v8 • Open Source

🏛️ INSTITUTIONAL TRENDLINE v8 • Open Source
Adaptive S/R discovery with ML scoring, MTF confluence, and event-driven alerts
What it does (in one breath):
This indicator auto-discovers institutional-grade trendlines / dynamic support & resistance, scores them for quality using a dual-regime ML model (trend vs. range), validates them with multiple techniques (Theil–Sen, Huber, ATR/RSI/MACD/EMA, MTF confluence), then tracks breakouts, retests, failed breaks, proximity/touch events, and learns from outcomes to adapt over time. A visual panel summarizes stats, and optional heatmap/zones show where price is most “supported” or “capped”.
🚀 Quick Start (2 minutes)
Add to chart and leave defaults.
At the top of Inputs:
🎛️ Preset → choose your style: Scalper, Swing, Investor (or Custom).
🧬 Market Profile → pick Crypto/FX/Stocks + style or “Auto by Timeframe”.
Keep 🎯 Accuracy Mode = Quantum AI and ⚡ Performance = Maximum Quality if your device handles it.
Turn on 💥 Breakout Signals and 🚨 Alerts if you want notifications.
Read the right-side panel: Active Lines, Avg Q, Best Line, Market State, Nearest S/R, Top-3 lines, Pattern, Touch counts.
That’s it. You’ll see thinner, professional trendlines, small labels, optional zones, and tasteful break/retest markers.
🧠 How it works (plain English)
Discovery: It samples price pairs (with a swing-pivot bias) and fits many candidate lines.
Inlier-only R²: Instead of punishing outliers, it measures how tight touching bars are to a line.
ML Quality (0–100): Six signals (Touches, Volume @ touches, RSI, MACD, Volatility, Duration) are weighted differently for Trend vs Range regimes.
Validation: Rejects lines that disagree across Theil–Sen and Huber regressions (>15% slope deviation), fail slope/ATR filters, or lack MTF confluence.
Live tracking: Once a line is on the chart, the script watches for Breakouts → Retests → Failed breaks, and logs outcomes to continually re-weight the ML model (if enabled).
🎛️ Inputs (top section first)
1) Presets & Profiles (at the top)
🎛️ Preset
Scalper – lower lookbacks, faster, more signals.
Swing – balanced lookbacks, 2–4 lines per window.
Investor – longer lookbacks, fewer but stronger lines.
Custom – you control everything below.
🧬 Market Profile
Tailors thresholds for Crypto / FX / Stocks and your style (Scalper / Swing / Investor). Choose Auto by Timeframe to adapt from your chart resolution.
These two choices set “effective” requirements under the hood (min quality, R², proximity windows, cleanup cadence, etc.) so you don’t have to micromanage.
2) 🤖 Machine Learning Engine
Enable ML Enhancement – turns the adaptive scoring on/off.
ML Sensitivity – caps the maximum achievable score (lower = stricter).
Adaptive Learning – updates weights after each confirmed outcome.
Outcome Window (bars) & Target (ATR) – define when a breakout is counted as success or fail for learning.
Dual-Regime Models – separate weight sets for Trend and Range.
Tip: If results look “too picky,” raise ML Sensitivity slightly (e.g., 0.85→0.95).
3) 🎯 Accuracy & Filters
Minimum Touch Points / Quality / R² – base requirements for new lines.
Multi-Algorithm Validation – confirms slope across three regressions.
Volume / RSI / MACD / EMA / ATR filters – optional evidence checks.
No-Repaint Strict (HTF closed only) – for purists; fewer but cleaner MTF confirmations.
4) 🧠 Pro Logic / MTF
Swing-Anchored Sampling Bias – increases hits on meaningful swings.
HTF 1 / HTF 2 – reference frames for confluence (e.g., 4H & 1D).
HTF Bars to Scan / Touches Needed – how much agreement to demand.
Geometric Midline Agreement – proximity to HTF midlines (20-SMA).
Midline Distance Threshold (×ATR) – how strict that midline check is.
5) 💎 Visual System
Display Trendlines / Zones / Smart Labels / Breakout Signals / Heatmap – toggle pieces on/off.
Visual Theme & Color Intensity – pick a palette; v8 lines are thinner with subtle gradients.
Highlight Top-3 Lines – faint halo on the three highest-quality lines.
Limit Signal Markers / Bar – prevents clutter in fast moves.
Tip: For the cleanest chart: show Trendlines + Breakouts, keep Zones semi-transparent, and enable Heatmap only when you want confluence context.
6) 🚨 Alerts
Enable Smart Alerts – master switch.
Alert Quality Threshold – only alert for lines ≥ this Q%.
Base Proximity (ATR) & Slope-Adaptive Proximity – how close is “near”.
Retest / Failed-Break Windows – how long after a break to track.
Per-Line Cool-Off (bars) – spacing to avoid spam.
Consolidated JSON Alert/Bar – single JSON payload with all events per bar (great for bots).
Fire Inline Alerts (verbose) – pop real-time alerts the moment events occur.
Alert names (mapped to alertconditions):
🆕 New S/R Created
📍 Approaching Trendline
🎯 Touching Trendline
🟢 Bullish Breakout / 🔴 Bearish Breakdown
♻️ Bullish Retest / ♻️ Bearish Retest
⛔ Failed Break
7) ⚡ Performance
Performance Mode – quality vs speed.
Max New Lines per Lookback/Bar – caps how many fresh lines a bar can add.
Cleanup Interval (bars) & Max Lines to Keep – automatic memory & clutter control.
Theil–Sen Sampled Pairs – fewer = faster; more = robust.
📈 How to read the chart
Lines:
Color = Support (green) or Resistance (red) at current price.
Thickness/Style = relates to Quality and Touches (higher Q = slightly bolder).
Labels show a badge (💎 🏆 ⭐ ✅ 📊) with Q%. Tooltip lists touches, R², priceline, lookback, and which evidences are ON.
Zones: Soft confidence corridors around lines (ATR-scaled).
Heatmap: A faint background tint—dominant support, resistance, or neutral/confluence.
Break markers: tiny ▲ / ▼ (or 🚀/💀 when very strong). Retests and failed breaks are tagged separately.
Top-3 glow: subtle halo on the three best lines right now.
🧭 Trading workflow (example)
Scenario A – Trend continuation
Market panel shows TREND; Top-3 lines include two rising supports ≥90% Q.
Price approaches one of them → Touch → Bullish breakout above a local resistance line.
Wait for ♻️ Retest of that broken line from above; if RSI>50 & MACD>0 (shown in panel), open a long with stop just under the line or zone.
Exit partials at next resistance line; trail under the line.
Scenario B – Range fade
Panel says RANGE; heatmap is neutral/confluence.
Price tags a high-Q red line and prints Touch without breakout, while RSI>60 cools off.
Enter a mean-revert short with stop above the line; target midrange or next green line.
If a Bullish breakout fires during the trade → respect the Failed Break logic; exit quickly.
Scenario C – Breakout trader
Filter only lines with Q ≥ 90% and alerts ON.
When Breakout triggers with strength ≥ 4/7 (see panel), take a starter.
Add on Retest if it prints within your retest window and confluence still looks good.
Manage risk with ATR or zone width.
This is a levels & event indicator. It doesn’t replace your system; it gives objective lines and objective events around those lines.
✅ Best-practice setup
Presets/Profiles: Start with Swing + your Market Profile.
ML Sensitivity: 0.90–0.95 for most markets.
Alerts: Set Alert Quality ≥ 85–90, Cool-Off = 4–6 bars.
MTF: Use 4H + 1D on intraday; 1D + 1W on daily charts.
Clutter control: Max Lines ~200, Cleanup ~50 bars, Signal cap 6/bar (defaults are sensible).
No-repaint strict: Turn on for signal review; turn off if you want more frequent MTF confirmations in real time.
🔬 Research Mode (optional)
Enable 🧪 Research Mode to track win-rates by quality buckets. The panel shows Win% [80-85 / 85-90 / 90-95 / 95+] so you can calibrate your thresholds per market.
⚠️ Notes & limitations
This is open-source research software. Past performance ≠ future results.
Learning requires time: the ML engine adapts after outcomes; don’t expect instant magic.
Very low-liquidity symbols may produce fewer reliable lines; increase lookbacks or tighten filters.
MTF data uses request.security with no lookahead; turning No-Repaint Strict on can further reduce signals.
🧩 Troubleshooting
“Too many lines.” Raise Min Quality / R², lower Max Lines, or reduce cap per lookback.
“Too few lines.” Lower Min Quality a bit, raise ML Sensitivity, or choose an easier Preset/Market Profile.
“Alerts are spammy.” Raise Alert Quality, increase Cool-Off, increase Proximity threshold.
“Performance is slow.” Use Balanced / Fast, reduce Theil–Sen pairs, or extend Cleanup Interval.
📦 Included alertconditions (for one-click alert rules)
New S/R Created
Approaching Trendline
Touching Trendline
Bullish Breakout / Bearish Breakdown
Bullish Retest / Bearish Retest
Failed Break
Enjoy, share feedback, and feel free to fork.
If you publish ideas using it, please credit “INSTITUTIONAL TRENDLINE v8 • OS” so other traders can find the open-source original. Happy trading! 🫶
Adaptive S/R discovery with ML scoring, MTF confluence, and event-driven alerts
What it does (in one breath):
This indicator auto-discovers institutional-grade trendlines / dynamic support & resistance, scores them for quality using a dual-regime ML model (trend vs. range), validates them with multiple techniques (Theil–Sen, Huber, ATR/RSI/MACD/EMA, MTF confluence), then tracks breakouts, retests, failed breaks, proximity/touch events, and learns from outcomes to adapt over time. A visual panel summarizes stats, and optional heatmap/zones show where price is most “supported” or “capped”.
🚀 Quick Start (2 minutes)
Add to chart and leave defaults.
At the top of Inputs:
🎛️ Preset → choose your style: Scalper, Swing, Investor (or Custom).
🧬 Market Profile → pick Crypto/FX/Stocks + style or “Auto by Timeframe”.
Keep 🎯 Accuracy Mode = Quantum AI and ⚡ Performance = Maximum Quality if your device handles it.
Turn on 💥 Breakout Signals and 🚨 Alerts if you want notifications.
Read the right-side panel: Active Lines, Avg Q, Best Line, Market State, Nearest S/R, Top-3 lines, Pattern, Touch counts.
That’s it. You’ll see thinner, professional trendlines, small labels, optional zones, and tasteful break/retest markers.
🧠 How it works (plain English)
Discovery: It samples price pairs (with a swing-pivot bias) and fits many candidate lines.
Inlier-only R²: Instead of punishing outliers, it measures how tight touching bars are to a line.
ML Quality (0–100): Six signals (Touches, Volume @ touches, RSI, MACD, Volatility, Duration) are weighted differently for Trend vs Range regimes.
Validation: Rejects lines that disagree across Theil–Sen and Huber regressions (>15% slope deviation), fail slope/ATR filters, or lack MTF confluence.
Live tracking: Once a line is on the chart, the script watches for Breakouts → Retests → Failed breaks, and logs outcomes to continually re-weight the ML model (if enabled).
🎛️ Inputs (top section first)
1) Presets & Profiles (at the top)
🎛️ Preset
Scalper – lower lookbacks, faster, more signals.
Swing – balanced lookbacks, 2–4 lines per window.
Investor – longer lookbacks, fewer but stronger lines.
Custom – you control everything below.
🧬 Market Profile
Tailors thresholds for Crypto / FX / Stocks and your style (Scalper / Swing / Investor). Choose Auto by Timeframe to adapt from your chart resolution.
These two choices set “effective” requirements under the hood (min quality, R², proximity windows, cleanup cadence, etc.) so you don’t have to micromanage.
2) 🤖 Machine Learning Engine
Enable ML Enhancement – turns the adaptive scoring on/off.
ML Sensitivity – caps the maximum achievable score (lower = stricter).
Adaptive Learning – updates weights after each confirmed outcome.
Outcome Window (bars) & Target (ATR) – define when a breakout is counted as success or fail for learning.
Dual-Regime Models – separate weight sets for Trend and Range.
Tip: If results look “too picky,” raise ML Sensitivity slightly (e.g., 0.85→0.95).
3) 🎯 Accuracy & Filters
Minimum Touch Points / Quality / R² – base requirements for new lines.
Multi-Algorithm Validation – confirms slope across three regressions.
Volume / RSI / MACD / EMA / ATR filters – optional evidence checks.
No-Repaint Strict (HTF closed only) – for purists; fewer but cleaner MTF confirmations.
4) 🧠 Pro Logic / MTF
Swing-Anchored Sampling Bias – increases hits on meaningful swings.
HTF 1 / HTF 2 – reference frames for confluence (e.g., 4H & 1D).
HTF Bars to Scan / Touches Needed – how much agreement to demand.
Geometric Midline Agreement – proximity to HTF midlines (20-SMA).
Midline Distance Threshold (×ATR) – how strict that midline check is.
5) 💎 Visual System
Display Trendlines / Zones / Smart Labels / Breakout Signals / Heatmap – toggle pieces on/off.
Visual Theme & Color Intensity – pick a palette; v8 lines are thinner with subtle gradients.
Highlight Top-3 Lines – faint halo on the three highest-quality lines.
Limit Signal Markers / Bar – prevents clutter in fast moves.
Tip: For the cleanest chart: show Trendlines + Breakouts, keep Zones semi-transparent, and enable Heatmap only when you want confluence context.
6) 🚨 Alerts
Enable Smart Alerts – master switch.
Alert Quality Threshold – only alert for lines ≥ this Q%.
Base Proximity (ATR) & Slope-Adaptive Proximity – how close is “near”.
Retest / Failed-Break Windows – how long after a break to track.
Per-Line Cool-Off (bars) – spacing to avoid spam.
Consolidated JSON Alert/Bar – single JSON payload with all events per bar (great for bots).
Fire Inline Alerts (verbose) – pop real-time alerts the moment events occur.
Alert names (mapped to alertconditions):
🆕 New S/R Created
📍 Approaching Trendline
🎯 Touching Trendline
🟢 Bullish Breakout / 🔴 Bearish Breakdown
♻️ Bullish Retest / ♻️ Bearish Retest
⛔ Failed Break
7) ⚡ Performance
Performance Mode – quality vs speed.
Max New Lines per Lookback/Bar – caps how many fresh lines a bar can add.
Cleanup Interval (bars) & Max Lines to Keep – automatic memory & clutter control.
Theil–Sen Sampled Pairs – fewer = faster; more = robust.
📈 How to read the chart
Lines:
Color = Support (green) or Resistance (red) at current price.
Thickness/Style = relates to Quality and Touches (higher Q = slightly bolder).
Labels show a badge (💎 🏆 ⭐ ✅ 📊) with Q%. Tooltip lists touches, R², priceline, lookback, and which evidences are ON.
Zones: Soft confidence corridors around lines (ATR-scaled).
Heatmap: A faint background tint—dominant support, resistance, or neutral/confluence.
Break markers: tiny ▲ / ▼ (or 🚀/💀 when very strong). Retests and failed breaks are tagged separately.
Top-3 glow: subtle halo on the three best lines right now.
🧭 Trading workflow (example)
Scenario A – Trend continuation
Market panel shows TREND; Top-3 lines include two rising supports ≥90% Q.
Price approaches one of them → Touch → Bullish breakout above a local resistance line.
Wait for ♻️ Retest of that broken line from above; if RSI>50 & MACD>0 (shown in panel), open a long with stop just under the line or zone.
Exit partials at next resistance line; trail under the line.
Scenario B – Range fade
Panel says RANGE; heatmap is neutral/confluence.
Price tags a high-Q red line and prints Touch without breakout, while RSI>60 cools off.
Enter a mean-revert short with stop above the line; target midrange or next green line.
If a Bullish breakout fires during the trade → respect the Failed Break logic; exit quickly.
Scenario C – Breakout trader
Filter only lines with Q ≥ 90% and alerts ON.
When Breakout triggers with strength ≥ 4/7 (see panel), take a starter.
Add on Retest if it prints within your retest window and confluence still looks good.
Manage risk with ATR or zone width.
This is a levels & event indicator. It doesn’t replace your system; it gives objective lines and objective events around those lines.
✅ Best-practice setup
Presets/Profiles: Start with Swing + your Market Profile.
ML Sensitivity: 0.90–0.95 for most markets.
Alerts: Set Alert Quality ≥ 85–90, Cool-Off = 4–6 bars.
MTF: Use 4H + 1D on intraday; 1D + 1W on daily charts.
Clutter control: Max Lines ~200, Cleanup ~50 bars, Signal cap 6/bar (defaults are sensible).
No-repaint strict: Turn on for signal review; turn off if you want more frequent MTF confirmations in real time.
🔬 Research Mode (optional)
Enable 🧪 Research Mode to track win-rates by quality buckets. The panel shows Win% [80-85 / 85-90 / 90-95 / 95+] so you can calibrate your thresholds per market.
⚠️ Notes & limitations
This is open-source research software. Past performance ≠ future results.
Learning requires time: the ML engine adapts after outcomes; don’t expect instant magic.
Very low-liquidity symbols may produce fewer reliable lines; increase lookbacks or tighten filters.
MTF data uses request.security with no lookahead; turning No-Repaint Strict on can further reduce signals.
🧩 Troubleshooting
“Too many lines.” Raise Min Quality / R², lower Max Lines, or reduce cap per lookback.
“Too few lines.” Lower Min Quality a bit, raise ML Sensitivity, or choose an easier Preset/Market Profile.
“Alerts are spammy.” Raise Alert Quality, increase Cool-Off, increase Proximity threshold.
“Performance is slow.” Use Balanced / Fast, reduce Theil–Sen pairs, or extend Cleanup Interval.
📦 Included alertconditions (for one-click alert rules)
New S/R Created
Approaching Trendline
Touching Trendline
Bullish Breakout / Bearish Breakdown
Bullish Retest / Bearish Retest
Failed Break
Enjoy, share feedback, and feel free to fork.
If you publish ideas using it, please credit “INSTITUTIONAL TRENDLINE v8 • OS” so other traders can find the open-source original. Happy trading! 🫶
發行說明
Code cleanup,minor bug 🐛 fixed 發行說明
| Use case | Chart TF | **Preset** | **Market Profile** | **MTF (HTF1 / HTF2)** | **ML Sens.** | **Alert Q ≥** | **Min Touch** | Notes || --------------------- | -------: | ------------ | --------------------- | -------------------------- | ------------: | ------------: | ------------: | -------------------------------------------- |
| **Crypto – Scalper** | 1–15m | **Scalper** | **Crypto – Scalper** | **60 / 240** | **0.95** | **90** | **4** | Fast entries; keep *Top-3 Glow* ON. |
| **FX – Swing** | 1h–4h | **Swing** | **FX – Swing** | **240 / 1D** | **0.90** | **88** | **5** | Balanced; great for trend + retests. |
| **Stocks – Investor** | 1D–1W | **Investor** | **Stocks – Investor** | **1D / 1W** *(or 1W / 1M)* | **0.85–0.90** | **92** | **6** | Fewer lines; consider higher *Min Line Age*. |
Tip: Preset + Market Profile live at the top of the settings panel. You can still fine-tune anything after selecting them.
🔔 Alerts — 2 easy ways
A) Single-event alerts (human-readable)
Enable: Enable Smart Alerts (settings → Alerts group).
Create alert on the chart:
Condition → INSTITUTIONAL TRENDLINE v8 • OS
Event → pick one:
New S/R Created
Approaching Trendline
Touching Trendline
Bullish Breakout / Bearish Breakdown
Bullish Retest / Bearish Retest
Failed Break
Options → Once per bar close (recommended)
Notify → choose app/email/webhook as you like.
Use Alert Quality Threshold and Per-Line Cool-Off (bars) in the inputs to control how often alerts fire.
B) Consolidated JSON (one payload per bar)
For webhook/automation users who want all events in a single message.
Enable in inputs:
Enable Smart Alerts = ON
Consolidated JSON Alert/Bar = ON
Create alert:
Condition → INSTITUTIONAL TRENDLINE v8 • OS → Any alert() function call
Frequency → Once per bar close
Message field can be anything; the script sends its own JSON.
Example payload:
{
"source": "ITS-8-OS",
"bar_time": 1723929600000,
"events": [
{"event":"breakout_bull","q":92,"str":6},
{"event":"touch","q":88}
]
}
Possible event values:
new_sr, approach, touch, breakout_bull, breakout_bear, retest_bull, retest_bear, failed_break.
Quick tuning tips
Too many lines? Raise Minimum Quality, raise Minimum R², increase Minimum Line Age, or lower Max Lines to Keep.
Too few lines? Lower Minimum Quality slightly (e.g., −2.5), reduce Min Touch Points, or set ML Sensitivity toward 1.00.
Cleaner visuals: Keep Confidence Zones ON, but drop opacity via Color Intensity if you prefer a lighter touch.
🧼 How to reset the indicator to default (beginners)
If you changed a bunch of inputs and things look “broken,” you can restore the original defaults in seconds:
Method 1 — From the settings panel
Click the gear icon on the indicator’s title (or double-click the title).
In the bottom-left of the panel, click Defaults ▾.
Choose Reset settings.
This restores the author’s default settings shipped with the script.
(Optional) If you want your current setup to load every time, choose Save as default after you configure it.
Method 2 — Remove & re-add
Hover the indicator title → click ✖ Remove.
Add it again from Indicators → search “INSTITUTIONAL TRENDLINE v8 • Open Source”.
If you had previously “Saved as default,” the indicator will load your saved defaults. Use Method 1 → Reset settings to get the author’s defaults.
💡 Tip: Preset & Market Profile live at the top of the inputs. Switching those does not overwrite your saved defaults; it just sets the internal policy for this instance.
🚑 Quick troubleshooting (common gotchas)
No lines showing?
Make sure Display Trendlines is ON.
Lower Minimum Quality Score a touch (e.g., 90 → 87.5).
Reduce Minimum R² or Min Touch Points slightly.
If using No-Repaint Strict, remember MTF bars must close before lines pass validation.
Too many lines?
Raise Minimum Quality Score or Minimum R².
Increase Min Line Age and/or lower Max Lines to Keep.
Turn Top-3 Glow ON to visually emphasize only the best.
Colors/labels feel heavy?
Increase Color Intensity (higher number = lighter/clearer).
Set Visual Theme → Minimalist Clean for slim, pro visuals.
Reduce Limit Signal Markers / Bar.
Alerts firing too often?
Raise Alert Quality Threshold and Per-Line Cool-Off (bars).
Use Consolidated JSON to receive one compact payload per bar.
💾 Save a safe baseline (recommended)
Once you like your setup:
Open the settings → Defaults ▾ → Save as default (for this indicator only).
(Optional) Save a Chart Layout or a Template so your workspace (EMAs, colors, alerts) comes back exactly as you left it.
If TradingView pushes a script update and things look different, just use Defaults ▾ → Reset settings to get back to the author’s defaults, then re-apply your favorite tweaks.
開源腳本
本著TradingView的真正精神,此腳本的創建者將其開源,以便交易者可以查看和驗證其功能。向作者致敬!雖然您可以免費使用它,但請記住,重新發佈程式碼必須遵守我們的網站規則。
免責聲明
這些資訊和出版物並不意味著也不構成TradingView提供或認可的金融、投資、交易或其他類型的意見或建議。請在使用條款閱讀更多資訊。
開源腳本
本著TradingView的真正精神,此腳本的創建者將其開源,以便交易者可以查看和驗證其功能。向作者致敬!雖然您可以免費使用它,但請記住,重新發佈程式碼必須遵守我們的網站規則。
免責聲明
這些資訊和出版物並不意味著也不構成TradingView提供或認可的金融、投資、交易或其他類型的意見或建議。請在使用條款閱讀更多資訊。