Strategy · Pine Script v4 · On the chart

Paraboic SAR + Regression Channels + Supertrend

by DaniilOkrug· code credited to icewalk

This strategy overlays Parabolic SAR, linear regression channels, and Supertrend directly on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code234
Settings24inputs
LicenceMIT
Last update4 years ago15 Dec 2021

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

234 lines of Pine Script v4 from [Order] Paraboic SAR + Regression Channels + Supertrend.txt, published under MIT. Keep the author's credit and licence lines when you reuse it.

[Order] Paraboic SAR + Regression Channels + Supertrend.txt
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © icewalk

//@version=4
strategy("[Order] Paraboic SAR + Regression Channels + Supertrend", shorttitle="PRCS", overlay=true, max_bars_back = 5000, max_lines_count = 500)

// -- INPUT --

takeProfitPercent = input(title="TakeProfit(%)", type=input.float, defval=1, step=0.1, tooltip="0 - disable", group="TakeProfit") / 100
stopLossPercent = input(title="StopLoss(%)", type=input.float, defval=1, step=0.1, tooltip="0 - disable", group="StopLoss") / 100

// Parabolic SAR
showPSAR = input(title="Show Parabolic SAR", type=input.bool, defval=true, group="Parabolic SAR")
start = input(title="Start", type=input.float, step=0.001, defval=0.02, group="Parabolic SAR")
increment = input(title="Increment", type=input.float, step=0.001, defval=0.02, group="Parabolic SAR")
maximum = input(title="Maximum", type=input.float, step=0.01, defval=0.2, group="Parabolic SAR")
width = input(title="Point Width", type=input.integer, minval=1, defval=2, group="Parabolic SAR")
highlightStartPoints = input(title="Highlight Start Points ?", type=input.bool, defval=true, group="Parabolic SAR")
showLabels = input(title="Show Buy/Sell Labels ?", type=input.bool, defval=true, group="Parabolic SAR")
highlightState = input(title="Highlight State ?", type=input.bool, defval=true, group="Parabolic SAR")

// Regression channels
// showRegressionChannels = input(title="Show Regression channels", type=input.bool, defval=true, group="Regression channels")
src = input(title = "Source", type = input.source, defval = close, group="Regression channels")
len = input(title = "Length", defval = 100, minval = 3, group="Regression channels")
mult = input(title = "Channel Multiplier", type = input.float, defval = 2, minval = 0.1, group="Regression channels")
showinterval = input(title = "Show Channel", defval = true, group="Regression channels")
showhist = input(title = "Show Historical Broken Channels", defval = true, group="Regression channels")
showresult = input(title = "Print Slope", defval = true, group="Regression channels")
lw = input(title = "Line Width", defval = 2, group="Regression channels")
colup = input( title = "Color When Up", defval = color.green, group="Regression channels")
coldw = input( title = "Color When Down", defval = color.red, group="Regression channels")
colbr = input( title = "Color Of Broken Channel", defval = color.silver, group="Regression channels")
extendln = input(title = "Extend Line", defval = true, group="Regression channels")

// Supertrend
showSuperTrend = input(title="Show", type=input.bool, defval=false, group="Supertrend")
atrPeriod = input(10, "ATR Length", group="Supertrend")
factor = input(3, "Factor", group="Supertrend")

// -- INPUT END --

// -- Parabolic SAR --

var float takeProfit = na
var float stopLoss = na

psar = sar(start, increment, maximum)
dir = psar < close ? 1 : -1

psarColor = dir == 1 ? #3388bb : #fdcc02
psarPlot = plot(showPSAR ? psar : na, title="PSAR", style=plot.style_circles, linewidth=width, color=psarColor)

var color longColor = color.green
var color shortColor = color.red

buySignal = dir == 1 and dir[1] == -1
sellSignal = dir == -1 and dir[1] == 1

// plotshape(buySignal and highlightStartPoints and showPSAR ? psar : na, title="Long Start", location=location.absolute, style=shape.circle, size=size.tiny, color=longColor)
plotshape(buySignal and showLabels and showPSAR ? psar : na, title="Buy Label", text="B", location=location.absolute, style=shape.labelup, size=size.small, color=longColor, textcolor=color.white)
    
// plotshape(sellSignal and highlightStartPoints and showPSAR ? psar : na, title="Short Start", location=location.absolute, style=shape.circle, size=size.tiny, color=shortColor)
plotshape(sellSignal and showLabels and showPSAR ? psar : na, title="Sell Label", text="S", location=location.absolute, style=shape.labeldown, size=size.small, color=shortColor, textcolor=color.white)

midPricePlot = plot(ohlc4, title="", display=display.none)

fillColor = highlightState ? (dir == 1 ? longColor : shortColor) : na
fill(midPricePlot, psarPlot, title="Trade State Filling", color=fillColor)

changeCond = dir != dir[1]
alertcondition(changeCond, title="Alert: PSAR Direction Change", message="PSAR has changed direction!")
alertcondition(buySignal, title="Alert: PSAR Long", message="PSAR Long")
alertcondition(sellSignal, title="Alert: PSAR Short", message="PSAR Sell")

// Close by takeprofit
takeProfitLong_Condition = takeProfitPercent != 0 and strategy.position_size > 0 and crossover(close, takeProfit)
takeProfitShort_Condition = takeProfitPercent != 0 and strategy.position_size < 0 and crossunder(close, takeProfit)

plotshape(takeProfitLong_Condition, title="Long TakeProfit", style=shape.circle, location=location.abovebar, color=color.yellow, size=size.tiny)
plotshape(takeProfitShort_Condition, title="Short TakeProfit", style=shape.circle, location=location.belowbar, color=color.yellow, size=size.tiny)

if takeProfitLong_Condition
    takeProfit := na
    strategy.close_all(comment="TakeProfit")

if takeProfitShort_Condition
    takeProfit := na
    strategy.close_all(comment="TakeProfit")

// Close by stoploss
if stopLossPercent != 0 and strategy.position_size > 0 and crossunder(close, stopLoss)
    stopLoss := na
    strategy.close_all(comment="StopLoss")

if stopLossPercent != 0 and strategy.position_size < 0 and crossover(close, stopLoss)
    stopLoss := na
    strategy.close_all(comment="StopLoss")

// Open orders
if buySignal
    strategy.entry("Long", strategy.long)
    if takeProfitPercent > 0
        takeProfit := close * (1 + takeProfitPercent)
        
    if stopLossPercent > 0
        stopLoss := close * (1 - stopLossPercent)

if sellSignal
    strategy.entry("Short", strategy.short)
    if takeProfitPercent >  0
        takeProfit := close * (1 - takeProfitPercent)
    
    if stopLossPercent > 0
        stopLoss :=  close * (1 + stopLossPercent)
// -- Parabolic SAR end --

//-- Regression Channels --

getmedianslopes(_n, _y) =>
    // For each point, get slopes with other data points, and then calculate median 
    // _n :: number of pointstheil
    // _y :: source time series, e.g. close
    _S = array.new_float(0)
    _S1 = array.new_float(0)
    float _m = 0.0
    int _ntmp = _n
    if _n > 2
        for i = 0 to _n-1
            _S1 := array.new_float(0)
            for j = 0 to _n-1
                if i != j
                    array.push(_S1,(_y[i]-_y[j])/(j-i))
            _m := array.median(_S1)
            array.push(_S,_m)
    _S

intercepts(_src,_n,_mslope) =>
    // Get all intercepts (Y - mslope*X) 
    // _n :: number of data points
    // _mslope :: median slope determined by means of TS model
    _I = array.new_float(0)
    if _n > 2
        for i = 0 to _n-1
            array.push(_I,_src[_n-1-i] - _mslope*i)
    _I



truncate(_value, _decimals) =>
    // For output: Truncates a given float to a certain number of decimals
    _factor = pow(10, _decimals)
    int(_value * _factor) / _factor

rmsd(_src,_x,_a,_b,_n) =>
    float _rmsd = 0.0
    for i = 0 to _n-1
        _rmsd := _rmsd + pow(_src[i] -_a -_b*(_x-i),2)/_n
    sqrt(_rmsd)

// --- MAIN ---
// get estimate only for the last barstate
if (not showhist) and (not barstate.islast)
    len:=0

S = getmedianslopes(len, src)
mslope = array.median(S)
I = intercepts(src,len,mslope)
minter = array.median(I)

// apply estimator
int x1 = bar_index-len
int x2 = bar_index
float y1 = minter
float y2 = minter+mslope*(len-1)

//estimate prediction interval (as \pm mult*RMSD)
float rmse = 0.0
if showhist or barstate.islast 
    for j = 0 to len-1
        rmse := rmse + pow(src[j] - (minter + mslope*(len - j)), 2)/len
float dev = mult*sqrt(rmse)

// check if prediction interval is broken
bool isbroken = (src > y2 + dev) or (src < y2 - dev)

// plot results
line a = line.new(x1, y1, x2, y2, xloc.bar_index, 
                  extend = extendln?extend.right:extend.none, 
                  color=mslope>0?colup:coldw, width=lw)
line.delete(a[1])
if showinterval
    line ap = line.new(x1, y1+dev, x2, y2+dev, xloc.bar_index, 
                      extend = extendln?extend.right:extend.none, 
                      color=isbroken?colbr:mslope>0?colup:coldw, 
                      width=lw, style=line.style_dashed)
    line am = line.new(x1, y1-dev, x2, y2-dev, xloc.bar_index, 
                      extend = extendln?extend.right:extend.none, 
                      color=isbroken?colbr:mslope>0?colup:coldw, 
                      width=lw, style=line.style_dashed)
    line.delete(ap[1])
    line.delete(am[1])
if showresult and barstate.islast
    label b = label.new(bar_index-(len-1), mslope>0?y1-dev:y1+dev, 
                       style = mslope>0?label.style_label_up:label.style_label_down, 
                       text = "Slope "+tostring(truncate(mslope,2)), 
                       color = mslope>0?colup:coldw)
    label.delete(b[1])

// handle the historical breaks
var int lastsavedbreakbar = 0
bool iscrossing = false
if cross(src, y2 + dev)
    iscrossing := true
bool histplotcondition = bar_index-int(len*0.5) > lastsavedbreakbar[1]
if iscrossing and showhist and histplotcondition
    line ap_broken = line.new(x1, y1+dev[1], x2, y2+dev[1], xloc.bar_index, 
                              extend = extend.none, 
                              color=colbr, width=1, style=line.style_dashed)
    line am_broken = line.new(x1, y1-dev[1], x2, y2-dev[1], xloc.bar_index, 
                              extend = extend.none, 
                              color=colbr, width=1, style=line.style_dashed)
    lastsavedbreakbar := bar_index

// -- SuperTrend --

[supertrend, direction] = supertrend(factor, atrPeriod)

bodyMiddle = plot(showSuperTrend ? (open + close) / 2 : na, display=display.none)
upTrend = plot(showSuperTrend and direction < 0 ? supertrend : na, "Up Trend", color = color.green, style=plot.style_linebr)
downTrend = plot(showSuperTrend and direction > 0 ? supertrend : na, "Down Trend", color = color.red, style=plot.style_linebr)

// fill(bodyMiddle, upTrend, supertrend ? color.new(color.green, 90) : color.new(color.green, 100), fillgaps=false)
// fill(bodyM1ddle, downTrend, supertrend ? color.new(color.red, 90) : color.new(color.red, 100), fillgaps=false)

Overview

Paraboic SAR + Regression Channels + Supertrend identifies directional momentum shifts when Parabolic SAR flips, issuing buy and sell signals. Position exits are controlled using customizable percentage-based take profit and stop loss levels. Settings allow traders to adjust indicator parameters, toggle channel visualization options, display slope values, and customize visual state highlights.

Details

Published by

DaniilOkrug on GitHub

Code credit

icewalk, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Trend, Support & resistance

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • The strategy enters trades without a stop loss

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
TakeProfit(%)float1takeProfitPercent
StopLoss(%)float1stopLossPercent
Show Parabolic SARbooltrueshowPSAR
Startfloat0.02start
Incrementfloat0.02increment
Maximumfloat0.2maximum
Point Widthint2width
Highlight Start Points ?booltruehighlightStartPoints
Show Buy/Sell Labels ?booltrueshowLabels
Highlight State ?booltruehighlightState
Sourcesourceclosesrc
Lengthint100len
Show all 24 settings
SettingTypeDefaultVariable
Channel Multiplierfloat2mult
Show Channelbooltrueshowinterval
Show Historical Broken Channelsbooltrueshowhist
Print Slopebooltrueshowresult
Line Widthint2lw
Color When Upcolorcolor.greencolup
Color When Downcolorcolor.redcoldw
Color Of Broken Channelcolorcolor.silvercolbr
Extend Linebooltrueextendln
ShowboolfalseshowSuperTrend
ATR Lengthint10atrPeriod
Factorint3factor
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

This trend-following strategy executes a classic Donchian channel breakout system designed to cross-validate backtest results against external framework benchmarks. It triggers a long entry when the closing price breaks above the highest high of the prior entr

Strategy v6 BreakoutTrend
Updated today · AGPL-3.0 GitHub repository of Forven S01509 - Simple Donchian 20/10 Breakout

Omar Edited WF

by Alorse
330 stars

Omar Edited WF is a trading strategy overlay built around Williams Fractals and multiple Exponential Moving Averages. It detects high and low fractal pivot points over configurable lookback periods alongside three adjustable EMA trendlines. Long entries are ma

Strategy v5 TrendMoving averages
Updated 2 months ago · None stated GitHub repository of Omar Edited WF
257 stars

This strategy calculates dynamic support and resistance levels using pivot highs and lows alongside a custom smoothed trend filter and a 3-period EMA. It identifies entry opportunities when price breaks out relative to the trend filter and short-term EMA cross

Strategy v5 TrendSupport & resistance Repaints
Updated 6 weeks ago · None stated GitHub repository of 30s - ES 1m Strategy Candle Bar
106 stars

This overlay strategy plots a two-timeframe Ichimoku setup on the price chart, with Tenkan, Kijun, Chikou, and Kumo from a base higher timeframe and an optional highest-timeframe cloud. It allows two entries in the same direction and uses ATR-based trailing st

Strategy v4 TrendVolatility & bands
Updated 2 years ago · GPL-3.0 GitHub repository of 2Tier Ichimoku Pyramiding [Takazudo]
104 stars

This strategy combines three Exponential Moving Averages with Williams Fractals to execute trend-following or mean-reverting trades. It analyzes price structure using short, medium, and long-term EMAs along with fractal highs and lows. Entries trigger when fra

Strategy v5 TrendMoving averages
Updated 3 years ago · MIT GitHub repository of 3MA and Fractals Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers