Swing TP/SL UltimateSwing TP/SL Ultimate
TradingView Pine Script v6 — Overlay Indicator
Short title: TP/SL▲▼ | Version: 2.0 | Type: Overlay Indicator
Overview
Swing TP/SL Ultimate is an advanced Take Profit and Stop Loss analysis tool for TradingView. Instead of requiring you to manually set fixed TP/SL percentages, it automatically calculates statistically-derived average TP and SL distances by studying every confirmed Swing High and Swing Low in historical price data across multiple timeframes and pivot lengths.
The core idea: the market's own past behaviour tells you how far it typically moves up (TP) and down (SL) from any given point. This indicator collects hundreds of those data points, filters out outliers, and surfaces the most reliable average — displayed as both a percentage and an actual price level on your chart.
Key Features
Multi-length Pivot DetectionSimultaneously scans 3 configurable pivot lengths (Fast / Mid / Slow) to maximise the number of valid swing samples
Multi-TimeFrame (HTF) PivotsImports pivots from a Higher TimeFrame and merges them into
the same statistical buffer
4 Averaging MethodsSimple, EMA-Weighted, Trimmed Mean, and Blended — all computed in parallel
Per-Bar ATR-Style AverageUses every bar's high−open and open−low as additional TP/SL samples for maximum data density
KNN High/Low PredictionA K-Nearest Neighbours model predicts the likely High and Low over the next 5 bars using 10 market features
Buy / Sell SignalsFires when price reaches a confirmed swing extreme, RSI confirms, and optional volume confirmation passes
Scalable DashboardFour size presets (Tiny / Small / Medium / Large) with compact mode for minimal screen space
Dual-format ValuesEvery metric is shown as both % and actual price — e.g. 2.34% (48,250.00)
Opaque Line LabelsLabels sit directly on chart lines with solid dark backgrounds so they block the line rather than overlap it
How It Works
1. Pivot Collection
A Swing High is a bar whose high is the highest of the N bars before it and the N bars after it. TradingView confirms this N bars after the fact. The indicator runs this detection three times simultaneously with different lengths:
Fast pivot (default N=5) — captures minor swings, many samples
Mid pivot (default N=10) — captures medium swings
Slow pivot (default N=21) — captures major swings, fewer but stronger signals
HTF pivot (default N=10 on 60m) — imported from higher timeframe
Every confirmed pivot feeds into a unified rolling array buffer shared by all four sources.
2. Percentage Calculation
For each confirmed Swing High pivot:
TP% sample = (pivotHigh − confirmClose) / confirmClose × 100
For each confirmed Swing Low pivot:
SL% sample = (confirmClose − pivotLow) / confirmClose × 100
Only positive values are stored. The buffer is capped at Rolling Buffer Size entries — when full, the oldest sample is dropped (FIFO), keeping the average adaptive to the current market regime.
3. Averaging Methods
All four methods run simultaneously. You choose which one drives the final Suggested TP/SL prices:
Simple Average
The arithmetic mean of all samples in the rolling buffer. Straightforward and transparent.
EMA-Weighted Average
A running Exponential Moving Average applied to each new pivot sample as it arrives. Recent pivots are weighted more heavily than older ones, making this method more responsive to regime changes.
α = 2 / (EMA Period + 1)
emaTP = emaTP × (1 − α) + newSample × α
Trimmed Mean (default)
Sorts all buffer samples and removes the top and bottom N% before computing the mean. This eliminates the influence of extreme outlier swings (e.g. a flash crash or a parabolic spike) that would otherwise skew the average.
Default trim: 10% → removes top 10% and bottom 10% of samples
Blended
Averages the Trimmed Mean result with the Per-Bar ATR-style result. Combines the statistical robustness of pivot-based sampling with the high data density of per-bar measurement.
4. Per-Bar ATR-Style Sampling
In addition to pivot-based samples, every single bar contributes:
barTP% = (high − open) / open × 100 ← upside potential per bar
barSL% = (open − low) / open × 100 ← downside risk per bar
An EMA is applied to both series. This gives the indicator a very high sample count (one per bar vs. one per pivot event) and closely mirrors the concept of Average True Range expressed directionally as a percentage.
KNN Prediction
The indicator includes a K-Nearest Neighbours (KNN) machine learning model that predicts how far price is likely to move up and down over the next 5 bars.
Feature Vector (10 dimensions)
#FeatureWhat it captures0RSI (14)Momentum / overbought / oversold1Distance from EMA-50 %Trend deviation2ATR (14) as % of priceVolatility regime3Bollinger Band position %Price within range4Volume vs. 20-bar SMA %Volume spike detection5Candle body size %Bar strength6Upper wick %Rejection at highs7Lower wick %Rejection at lows8Momentum (10-bar) %Short-term trend force9Close position in 20-bar range %Range context
Algorithm
For every bar in the training window (up to 200 bars back, sampled every 2 bars for performance), compute the Euclidean distance between the current bar's feature vector and that historical bar's feature vector.
Select the K nearest historical bars (default K=5).
For each neighbour, look up what actually happened over the next 5 bars: how high did price go, how low did it go.
Weight each neighbour by inverse distance — closer matches contribute more.
The weighted average of future highs and lows becomes the KNN prediction.
The result is plotted as a dotted forward line on the chart and shown in the dashboard.
Buy / Sell Signals
Signals fire only when all conditions are simultaneously true.
Buy Signal (▲ BUY — green label below bar)
ConditionLogicNear Swing Lowclose ≤ lastSwingLow × (1 + avgSL% × 0.5)RSI OversoldRSI ≤ Oversold threshold (default 35)Bullish candleclose > openVolume (optional)volume > 20-bar SMA × 1.2
Sell Signal (▼ SELL — red label above bar)
ConditionLogicNear Swing Highclose ≥ lastSwingHigh × (1 − avgTP% × 0.5)RSI OverboughtRSI ≥ Overbought threshold (default 65)Bearish candleclose < openVolume (optional)volume > 20-bar SMA × 1.2
Note: Signals are contextual alerts, not a complete trading system. Always combine with your own analysis and risk management.
Dashboard
The on-chart table updates on every bar. Its size, position, and content depth are all configurable.
Size Presets
SizeTextRows shownTinytinyCore only (compact)SmallsmallCore + method breakdownMediumnormalCore + breakdown + range statsLargelargeFull: all above + KNN + signal state + HTF status
Dashboard Sections
Always visible
RowLabelDescriptionTitle⬡ TP / SL ULTIMATEActive method + sample countsLive▲ To Swing HIGH% and price distance to last pivot highLive▼ To Swing LOW% and price distance to last pivot lowAvg★ Avg TP (Final)Final averaged TP as % and suggested priceAvg★ Avg SL (Final)Final averaged SL as % and suggested priceAvg⚖ R:R RatioavgTP ÷ avgSL — green ≥2.0, yellow ≥1.0, red <1.0
Small and above
RowLabelDescriptionBreakdownSimple / EMA-Weighted / Trimmed / Per-BarTP% / SL% for each method side by side
Medium and above
RowLabelDescriptionRangeAvg High %Mean upside from all pivot samplesRangeMax / Min High %Best and worst upside seen in bufferRangeAvg Low %Mean downside from all pivot samplesRangeMax Low %Worst downside seen in buffer
Large only
RowLabelDescriptionKNNKNN Pred High +%Predicted upside over next 5 bars (% + price)KNNKNN Pred Low −%Predicted downside over next 5 bars (% + price)SignalRSICurrent RSI value, colour-codedSignalVolume vs SMACurrent volume as % of 20-bar SMASignalActive SignalBUY / SELL / WaitingInfoHTF PivotsWhether HTF pivot collection is active
Chart Visuals
ElementColourDescriptionDashed green lineGreenLast confirmed Swing High levelDashed red lineRedLast confirmed Swing Low levelSolid teal lineTealAvg TP suggested priceSolid orange lineOrangeAvg SL suggested priceDotted purple linePurpleKNN predicted High (forward projection)Dotted fuchsia lineFuchsiaKNN predicted Low (forward projection)▼ triangle above barRedConfirmed pivot high marker▲ triangle below barLimeConfirmed pivot low markerBUY labelLimeBuy signal — all conditions metSELL labelRedSell signal — all conditions met
All lines carry opaque labels (solid dark background matching the line colour) placed directly on the line so the text is legible without the line running through it.
Input Reference
📐 Pivot Detection
InputDefaultRangeDescriptionPivot Length 1 – Fast52–50Left/right bars to confirm a fast swingPivot Length 2 – Mid102–100Left/right bars for mid-grade swingPivot Length 3 – Slow212–200Left/right bars for slow/major swingRolling Buffer Size15020–500Max samples kept per side (TP / SL)Outlier Trim %100–40% of extremes removed from trimmed meanEMA Weight Period142–100Smoothing for EMA-weighted averagePer-Bar EMA Length20010–1000EMA length for per-bar ATR-style average
🌐 Multi-TimeFrame
InputDefaultDescriptionEnable HTF PivotsOnAdds higher-timeframe pivots to the bufferHigher TimeFrame60 (1H)Source timeframe for HTF pivotsHTF Pivot Length10Pivot detection length on the higher timeframe
🤖 KNN Prediction
InputDefaultRangeDescriptionEnable KNNOn—Toggle the KNN engine on/offK Neighbours53–15Number of nearest matches to useKNN Training Window10030–200How many bars back to search
📊 Averaging
InputDefaultOptionsDescriptionPrimary Pivot MethodTrimmed MeanSimple / EMA Weighted / Trimmed Mean / BlendedWhich pivot average drives the final outputSample SourceBlendedPivot Only / Per-Bar Only / BlendedWhat data feeds the final TP/SL
🎯 Signals
InputDefaultDescriptionShow Buy/Sell SignalsOnMaster toggle for signal markersRSI Length14Period for RSI calculationRSI Oversold – Buy35RSI threshold to confirm a buyRSI Overbought – Sell65RSI threshold to confirm a sellVolume ConfirmationOnRequire volume > 1.2× SMA to trigger
🖥 Dashboard
InputDefaultOptionsDescriptionPositionTop RightTop/Bottom × Left/RightCorner placement of the tableDashboard SizeMediumTiny / Small / Medium / LargeControls text size and row countUltra-Compact ModeOff—Shows only title + 6 core rows
🎨 Visuals
InputDefaultDescriptionShow Pivot Level LinesOnDashed lines at last Swing High / LowShow Avg TP/SL LinesOnSolid lines at suggested TP and SL pricesShow KNN Predicted LinesOnDotted forward lines from KNN modelShow Pivot MarkersOnTriangles at confirmed pivot barsShow Line LabelsOnOpaque labels on all chart lines
Recommended Settings by Use Case
Scalping (1m – 5m charts)
Pivot Length 1: 3 Pivot Length 2: 5 Pivot Length 3: 10
HTF Timeframe: 15
Buffer Size: 100 EMA Period: 7 Per-Bar EMA: 50
Primary: EMA Weighted Source: Blended
RSI Oversold: 30 RSI Overbought: 70
Swing Trading (1H – 4H charts)
Pivot Length 1: 5 Pivot Length 2: 10 Pivot Length 3: 21
HTF Timeframe: D
Buffer Size: 150 EMA Period: 14 Per-Bar EMA: 200
Primary: Trimmed Mean Source: Blended
RSI Oversold: 35 RSI Overbought: 65
Position Trading (Daily – Weekly charts)
Pivot Length 1: 10 Pivot Length 2: 20 Pivot Length 3: 50
HTF Timeframe: W
Buffer Size: 200 EMA Period: 21 Per-Bar EMA: 500
Primary: Simple Source: Pivot Only
RSI Oversold: 40 RSI Overbought: 60
Technical Notes
Pine Script version: v6
Type: indicator() with overlay=true
Max lines: 20 | Max labels: 50
MTF data: Uses barmerge.lookahead_off to prevent future-leak
KNN performance: Samples every 2nd bar in the training window; hard-capped at 200 bars to stay within Pine's execution time limits
Global scope rule: All plotshape() calls and var mutations are placed at the global scope as required by Pine Script v6
Changelog
VersionDateChanges1.0InitialBasic pivot avg + dashboard2.0CurrentKNN engine, MTF pivots, 4 avg methods, buy/sell signals, 4 dashboard sizes, opaque line labels, full Pine v6 scope compliance
Built for TradingView Pine Script v6. For educational and analytical purposes only — not financial advice.
Chỉ báo Pine Script®






















