OPEN-SOURCE SCRIPT
Theil-Sen Line Filter [BackQuant]

Theil-Sen Line Filter [BackQuant]
A robust, median-slope baseline that tracks price while resisting outliers. Designed for the chart pane as a clean, adaptive reference line with optional candle coloring and slope-flip alerts.
What this is
A trend filter that estimates the underlying slope of price using a Theil-Sen style median of past slopes, then advances a baseline by a controlled fraction of that slope each bar. The result is a smooth line that reacts to real directional change while staying calm through noise, gaps, and single-bar shocks.
Why Theil-Sen
Classical moving averages are sensitive to outliers and shape changes. Ordinary least squares is sensitive to large residuals. The Theil-Sen idea replaces a single fragile estimate with the median of many simple slopes, which is statistically robust and less influenced by a few extreme bars. That makes the baseline steadier in choppy conditions and cleaner around regime turns.
What it plots
How it behaves (high level)
Inputs and what they do
How to read it
Use cases
Tuning guidance
Alerts included
Strengths
Notes
This is a filter, not a trading system. It does not account for execution, spreads, or gaps. Pair it with entry logic, risk management, and higher-timeframe context if you plan to use it for decisions.
A robust, median-slope baseline that tracks price while resisting outliers. Designed for the chart pane as a clean, adaptive reference line with optional candle coloring and slope-flip alerts.
What this is
A trend filter that estimates the underlying slope of price using a Theil-Sen style median of past slopes, then advances a baseline by a controlled fraction of that slope each bar. The result is a smooth line that reacts to real directional change while staying calm through noise, gaps, and single-bar shocks.
Why Theil-Sen
Classical moving averages are sensitive to outliers and shape changes. Ordinary least squares is sensitive to large residuals. The Theil-Sen idea replaces a single fragile estimate with the median of many simple slopes, which is statistically robust and less influenced by a few extreme bars. That makes the baseline steadier in choppy conditions and cleaner around regime turns.
What it plots
- Filtered baseline that advances by a fraction of the robust slope each bar.
- Optional candle coloring by baseline slope sign for quick trend read.
- Alerts when the baseline slope turns up or down.
How it behaves (high level)
- Looks back over a fixed window and forms many “current vs past” bar-to-bar slopes.
- Takes the median of those slopes to get a robust estimate for the bar.
- Optionally caps the magnitude of that per-bar slope so a single volatile bar cannot yank the line.
- Moves the baseline forward by a user-controlled fraction of the estimated slope. Lower fractions are smoother. Higher fractions are more responsive.
Inputs and what they do
- Price Source — the series the filter tracks. Typical is close; HL2 or HLC3 can be smoother.
- Window Length — how many bars to consider for slopes. Larger windows are steadier and slower. Smaller windows are quicker and noisier.
- Response — fraction of the estimated slope applied each bar. 1.00 follows the robust slope closely; values below 1.00 dampen moves.
- Slope Cap Mode — optional guardrail on each bar’s slope:
None — no cap.
ATR — cap scales with recent true range.
Percent — cap scales with price level.
Points — fixed absolute cap in price points.
- ATR Length / Mult, Cap Percent, Cap Points — tune the chosen cap mode’s size.
- UI Settings — show or hide the line, paint candles by slope, choose long and short colors.
How to read it
- Up-slope baseline and green candles indicate a rising robust trend. Pullbacks that do not flip the slope often resolve in trend direction.
- Down-slope baseline and red candles indicate a falling robust trend. Bounces against the slope are lower-probability until proven otherwise.
- Flat or frequent flips suggest a range. Increase window length or decrease response if you want fewer whipsaws in sideways markets.
Use cases
- Bias filter — only take longs when slope is up, shorts when slope is down. It is a simple way to gate faster setups.
- Stop or trail reference — use the line as a trailing guide. If price closes beyond the line and the slope flips, consider reducing exposure.
- Regime detector — widen the window on higher timeframes to define major up vs down regimes for asset rotation or risk toggles.
- Noise control — enable a cap mode in very volatile symbols to retain the line’s continuity through event bars.
Tuning guidance
- Quick swing trading — shorter window, higher response, optionally add a percent cap to keep it stable on large moves.
- Position trading — longer window, moderate response. ATR cap tends to scale well across cycles.
- Low-liquidity or gappy charts — prefer longer window and a points or ATR cap. That reduces jumpiness around discontinuities.
Alerts included
- Theil-Sen Up Slope — baseline’s one-bar change crosses above zero.
- Theil-Sen Down Slope — baseline’s one-bar change crosses below zero.
Strengths
- Robust to outliers through median-based slope estimation.
- Continuously advances with price rather than re-anchoring, which reduces lag at turns.
- User-selectable slope caps to tame shock bars without over-smoothing everything.
- Minimal visuals with optional candle painting for fast regime recognition.
Notes
This is a filter, not a trading system. It does not account for execution, spreads, or gaps. Pair it with entry logic, risk management, and higher-timeframe context if you plan to use it for decisions.
오픈 소스 스크립트
진정한 트레이딩뷰 정신에 따라 이 스크립트 작성자는 트레이더가 기능을 검토하고 검증할 수 있도록 오픈소스로 공개했습니다. 작성자에게 찬사를 보냅니다! 무료로 사용할 수 있지만 코드를 다시 게시할 경우 하우스 룰이 적용된다는 점을 기억하세요.
Check out whop.com/signals-suite for Access to Invite Only Scripts!
면책사항
이 정보와 게시물은 TradingView에서 제공하거나 보증하는 금융, 투자, 거래 또는 기타 유형의 조언이나 권고 사항을 의미하거나 구성하지 않습니다. 자세한 내용은 이용 약관을 참고하세요.
오픈 소스 스크립트
진정한 트레이딩뷰 정신에 따라 이 스크립트 작성자는 트레이더가 기능을 검토하고 검증할 수 있도록 오픈소스로 공개했습니다. 작성자에게 찬사를 보냅니다! 무료로 사용할 수 있지만 코드를 다시 게시할 경우 하우스 룰이 적용된다는 점을 기억하세요.
Check out whop.com/signals-suite for Access to Invite Only Scripts!
면책사항
이 정보와 게시물은 TradingView에서 제공하거나 보증하는 금융, 투자, 거래 또는 기타 유형의 조언이나 권고 사항을 의미하거나 구성하지 않습니다. 자세한 내용은 이용 약관을 참고하세요.