Strategy · Pine Script v4 · On the chart

TrendSignal + Supertrend Strategy

by DaniilOkrug· code credited to icewalk

TrendSignal + Supertrend Strategy detects trend changes using a custom indicator based on recent high-low ranges and a percentage K value calculated from RISK input.

View on GitHub

GitHub stars2on the repository
Pine versionv4older, still runs
Lines of code106
Settings5inputs
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

106 lines of Pine Script v4 from trendsignal + supertrend strategy.txt, published under MIT. Keep the author's credit and licence lines when you reuse it.

trendsignal + supertrend strategy.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("trendsignal + supertrend strategy", overlay=true, margin_long=100, margin_short=100, default_qty_type=strategy.percent_of_equity, default_qty_value=50)

//---INPUT---

RISK = input(3, title="RISK", type=input.integer)
Alert_Delay_In_Seconds = input(0, title="Alert_Delay_In_Seconds", type=input.integer)
alertsOn = input(false, title="Включить оповещения?", type=input.bool)

//---INPUT END---

bool isBuy = na

int SSP = 9
var int PrevAlertTime = 0
var float alertBar = 0

var int K = na
float Range = 0
float AvgRange = 0
var float smin = na
var float smax = na
var float SsMax = na
var float SsMin = na
var float price = na
var bool uptrend = na
var bool old = false

int limit = 1 + SSP

K := 33 - RISK
for shift = limit to 0
    for i = shift to (shift + SSP)
        AvgRange += high[i] - low[i]
        
    Range := AvgRange / (SSP + 1)
    
    SsMax := high[shift]
    SsMin := low[shift]
    for i = shift to (shift + SSP - 1)
        price := high[i]
        if SsMax < price
            SsMax := price
        price := low[i]
        if SsMin > price
            SsMin := price
            
    smin := SsMin + (SsMax - SsMin)*K/100
    smax := SsMax - (SsMax - SsMin)*K/100
    
    if close[shift] < smin
        uptrend := false
    
    if close[shift] > smax
        uptrend := true
    
    if uptrend != old and uptrend == true
        
        if bar_index > alertBar and shift == 0
            isBuy := true
            alertBar := bar_index
            PrevAlertTime := time
    
    if uptrend != old and uptrend == false and (time - PrevAlertTime > 1 * Alert_Delay_In_Seconds)
        
        if bar_index > alertBar and shift == 0  and (time - PrevAlertTime > 1 * Alert_Delay_In_Seconds)
            isBuy := false
            alertBar := bar_index
            PrevAlertTime := time
    
    old := uptrend

plotshape(isBuy == true, title="Buy", style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small)
plotshape(isBuy == false, title="Sell", style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small)

//---trendsignal END---

atrPeriod = input(10, "ATR Length")
factor = input(3, "Factor")

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

fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps=false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps=false)

//---------------------

if close > supertrend
    if strategy.position_size < 0
        strategy.close_all()
if close < supertrend
    if strategy.position_size > 0
        strategy.close_all()
        
if isBuy == true and close > supertrend
    strategy.entry("long", strategy.long)
    alert("BUY", alert.freq_once_per_bar)
if isBuy == false and close < supertrend
    strategy.entry("short", strategy.short)
    alert("SELL", alert.freq_once_per_bar)

Overview

TrendSignal + Supertrend Strategy sets buy or sell signals when the trend shifts. Supertrend is overlaid using ATR period and factor settings to determine trend direction. The strategy enters long positions when isBuy is true and close exceeds Supertrend, and shorts when false and close falls below Supertrend. It closes all positions on opposite signals. Supertrend lines and buy/sell shapes are drawn directly on the price chart. Main settings adjust trend sensitivity via RISK and Supertrend parameters via ATR length and factor. Default position sizing is 50 percent of equity. No exit rules are defined beyond signal reversal. It draws on the price chart.

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, Volatility & bands

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
RISKint3RISK
Alert_Delay_In_Secondsint0Alert_Delay_In_Seconds
Включить оповещения?boolfalsealertsOn
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

330 stars

This strategy calculates Bollinger Bands and Aroon oscillator values to identify mean-reversion opportunities. It enters a long position using full equity when the closing price crosses below the lower Bollinger Band while Aroon Up remains above a user-specifi

Strategy v5 Mean reversionVolatility & bands
Updated 2 months ago · None stated GitHub repository of Bollinger bands + Aroon [Alorse]
257 stars

This overlay strategy targets one-minute ES futures and plots volume-weighted moving-average bands from the open, scaled by a standard-deviation multiple, plus a slower band from ten-minute opens. A higher-timeframe exponential moving average can filter trades

Strategy v6 Moving averagesVolatility & bands
Updated 6 weeks ago · None stated GitHub repository of ES - Futures 1M No Repaint

STRG-BBForce

by harryguiacorn
219 stars

STRG-BBForce is a Bollinger Bands trend-following strategy. It calculates standard Bollinger Bands and tracks directional alignment across the upper, lower, and basis lines. When all three lines slope upward, it opens a long position and closes short positions

Strategy v5 TrendVolatility & bands
Updated 1 year ago · None stated GitHub repository of STRG-BBForce

Nasdaq Prop Firm Strategy

by TradersPost
218 stars

This strategy uses multiple VWAP anchors and a custom Lull indicator to generate buy and sell signals on the Nasdaq price chart. It plots the VWAP trend line and three VWAP anchors with customizable colors and mitigation methods. The Lull indicator produces si

Strategy v6 TrendSupport & resistance Repaints
Updated 3 months ago · None stated GitHub repository of Nasdaq Prop Firm Strategy

This strategy implements a single-layer perceptron machine learning model built from scratch to generate trading signals directly on the price chart. It calculates predictions based on sample size, threshold settings, and optional volatility or volume filters.

Strategy v5 AI / machine learningTrend
Updated 1 year ago · None stated GitHub repository of Machine Learning: Perceptron-Based Strategy [5] (v.3)
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]

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