Strategy · Pine Script v4 · On the chart

Trendsignal + Zig Zag Strategy

by DaniilOkrug· code credited to icewalk

This strategy identifies market direction by combining a TrendSignal breakout algorithm with a Zig Zag swing overlay.

View on GitHub

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

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

trendsignal + zigzag 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 + zig zag 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

// var int limit = bar_index - counted_bars
// if counted_bars == 0
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---

dev_threshold = input(title="Deviation (%)", type=input.float, defval=5.0, minval=0.00001, maxval=100.0)
depth = input(title="Depth", type=input.integer, defval=10, minval=1)
line_color = input(title="Line Color", defval=#2962FF)
extend_to_last_bar = input(title="Extend to Last Bar", defval=true)
display_reversal_price = input(title="Display Reversal Price", defval=true)
display_cumulative_volume = input(title="Display Cumulative Volume", defval=true)
display_reversal_price_change = input(title="Display Reversal Price Change", defval=true, inline="price rev")
difference_price = input("Absolute", "", options=["Absolute", "Percent"], inline="price rev")

pivots(src, length, isHigh) =>
    p = nz(src[length])
    if length == 0
        [bar_index, p]
    else
        isFound = true
        for i = 0 to length - 1
            if isHigh and src[i] > p
                isFound := false
            if not isHigh and src[i] < p
                isFound := false
        for i = length + 1 to 2 * length
            if isHigh and src[i] >= p
                isFound := false
            if not isHigh and src[i] <= p
                isFound := false
        if isFound and length * 2 <= bar_index
            [bar_index[length], p]
        else
            [int(na), float(na)]
[iH, pH] = pivots(high, floor(depth / 2), true)
[iL, pL] = pivots(low, floor(depth / 2), false)

calc_dev(base_price, price) =>
    100 * (price - base_price) / base_price

price_rotation_aggregate(price_rotation, pLast, cum_volume) =>
    str = ""
    if display_reversal_price
        str += tostring(pLast, format.mintick) + " "
    if display_reversal_price_change
        str += price_rotation + " "
    if display_cumulative_volume
        str += "\n" + cum_volume
    str

caption(isHigh, iLast, pLast, price_rotation, cum_volume) =>
    price_rotation_str = price_rotation_aggregate(price_rotation, pLast, cum_volume)
    if display_reversal_price or display_reversal_price_change or display_cumulative_volume
        if not isHigh
            label.new(iLast, pLast, text=price_rotation_str, style=label.style_none, yloc=yloc.belowbar, textcolor=color.red)
        else
            label.new(iLast, pLast, text=price_rotation_str, style=label.style_none, yloc=yloc.abovebar, textcolor=color.green)

price_rotation_diff(pLast, price) =>
    if display_reversal_price_change
        tmp_calc = price - pLast
        str = difference_price == "Absolute"? (sign(tmp_calc) > 0? "+" : "") + tostring(tmp_calc, format.mintick) : (sign(tmp_calc) > 0? "+" : "-") + tostring((abs(tmp_calc) * 100)/pLast, format.percent)
        str := "(" + str  + ")"
        str
    else
        ""
volume_sum(index1, index2) =>
    float CVI = 0
    for i = index1 + 1 to index2
        CVI += volume[bar_index - i]
    tostring(CVI, format.volume)

var line lineLast = na
var label labelLast = na
var int iLast = 0
var float pLast = 0
var bool isHighLast = true // otherwise the last pivot is a low pivot
var int linesCount = 0

pivotFound(dev, isHigh, index, price) =>
    if isHighLast == isHigh and not na(lineLast)
        // same direction
        if isHighLast ? price > pLast : price < pLast
            if linesCount <= 1
                line.set_xy1(lineLast, index, price)
            line.set_xy2(lineLast, index, price)
            label.set_xy(labelLast, index, price)
            label.set_text(labelLast, price_rotation_aggregate(price_rotation_diff(line.get_y1(lineLast), price), price, volume_sum(line.get_x1(lineLast), index)))
            [lineLast, labelLast, isHighLast, false]
        else
            [line(na), label(na), bool(na), false]
    else // reverse the direction (or create the very first line)
        if na(lineLast)
            id = line.new(index, price, index, price, color=line_color, width=2)
            lb = caption(isHigh, index, price, price_rotation_diff(pLast, price), volume_sum(index, index))
            [id, lb, isHigh, true]
        else
            // price move is significant
            if abs(dev) >= dev_threshold
                id = line.new(iLast, pLast, index, price, color=line_color, width=2)
                lb = caption(isHigh, index, price, price_rotation_diff(pLast, price), volume_sum(iLast, index))
                [id, lb, isHigh, true]
            else
                [line(na), label(na), bool(na), false]


if not na(iH) and not na(iL) and iH == iL
    dev1 = calc_dev(pLast, pH)
    [id2, lb2, isHigh2, isNew2] = pivotFound(dev1, true, iH, pH)
    if isNew2
        linesCount := linesCount + 1
    if not na(id2)
        lineLast := id2
        labelLast := lb2
        isHighLast := isHigh2
        iLast := iH
        pLast := pH
    dev2 = calc_dev(pLast, pL)
    [id1, lb1, isHigh1, isNew1] = pivotFound(dev2, false, iL, pL)
    if isNew1
        linesCount := linesCount + 1
    if not na(id1)
        lineLast := id1
        labelLast := lb1
        isHighLast := isHigh1
        iLast := iL
        pLast := pL
else
    if not na(iH)
        dev1 = calc_dev(pLast, pH)
        [id, lb, isHigh, isNew] = pivotFound(dev1, true, iH, pH)
        if isNew
            linesCount := linesCount + 1
        if not na(id)
            lineLast := id
            labelLast := lb
            isHighLast := isHigh
            iLast := iH
            pLast := pH
    else
        if not na(iL)
            dev2 = calc_dev(pLast, pL)
            [id, lb, isHigh, isNew] = pivotFound(dev2, false, iL, pL)
            if isNew
                linesCount := linesCount + 1
            if not na(id)
                lineLast := id
                labelLast := lb
                isHighLast := isHigh
                iLast := iL
                pLast := pL

var line extend_line = na
var label extend_label = na
if extend_to_last_bar == true and barstate.islast == true
    isHighLastPoint = not isHighLast
    curSeries = isHighLastPoint ? high : low
    if na(extend_line) and na(extend_label)
        extend_line := line.new(line.get_x2(lineLast), line.get_y2(lineLast), bar_index, curSeries, color=line_color, width=2)
        extend_label := caption(not isHighLast, bar_index, curSeries,  price_rotation_diff(line.get_y2(lineLast), curSeries), volume_sum(line.get_x2(lineLast), bar_index))

    line.set_xy1(extend_line, line.get_x2(lineLast), line.get_y2(lineLast))
    line.set_xy2(extend_line, bar_index, curSeries)
    label.set_xy(extend_label, bar_index, curSeries)
    price_rotation = price_rotation_diff(line.get_y1(extend_line), curSeries)
    volume_cum = volume_sum(line.get_x1(extend_line), bar_index)
    label.set_text(extend_label, price_rotation_aggregate(price_rotation, curSeries, volume_cum))
    label.set_textcolor(extend_label, isHighLastPoint? color.green : color.red)
    label.set_yloc(extend_label, yloc= isHighLastPoint? yloc.abovebar : yloc.belowbar)

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

if isBuy == true and isHighLast
    strategy.entry("long", strategy.long)
    alert("BUY", alert.freq_once_per_bar)
if isBuy == false and not isHighLast
    strategy.entry("short", strategy.short)
    alert("SELL", alert.freq_once_per_bar)

Overview

Trendsignal + Zig Zag Strategy calculates dynamic price bands over a period to determine trend flips, plotting triangle shapes directly on the price chart for buy and sell signals. Main inputs adjust the risk sensitivity factor, alert delay in seconds, and Zig Zag deviation percentage and depth. The script contains no default stop loss or take profit rules.

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, Breakout

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
Deviation (%)float5.0dev_threshold
Depthint10depth
Line Colorcolor#2962FFline_color
Extend to Last Barbooltrueextend_to_last_bar
Display Reversal Pricebooltruedisplay_reversal_price
Display Cumulative Volumebooltruedisplay_cumulative_volume
Display Reversal Price Changebooltruedisplay_reversal_price_change
difference_pricestringAbsolutedifference_price
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
257 stars

This strategy plots running pivot highs as red R circles and pivot lows as blue S circles directly on the price chart. It computes an EMA 3 and a Cto trend line from close prices, then generates long signals on upward EMA-Cto crossovers combined with price pos

Strategy v6 TrendMoving averages Repaints
Updated 6 weeks ago · None stated GitHub repository of Best Chart 1m Strategy Candle Bar
106 stars

Calculates multi-period logarithmic regression trend channels and deviation bands across up to twenty selectable lookback lengths directly on the price chart. It evaluates channel slopes and Pearson's correlation coefficient to detect market trends and generat

Strategy v5 TrendSupport & resistance Repaints
Updated 2 years ago · GPL-3.0 GitHub repository of Advanced Trend Detection Strategy

This trend breakout strategy plots Donchian Channels consisting of upper, lower, and middle bands directly on the main price chart. Long positions enter when price touches the upper channel and pulls back to or below the middle band, placing a stop loss at the

Strategy v6 TrendBreakout
Updated 2 months ago · MPL-2.0 GitHub repository of Donchian Strategy - Dynamic TP, Fixed SL, 1% Risk, Daily Target
43 stars

This strategy executes trades on short-term cryptocurrency charts using a combination of pivot support and resistance levels and a multi-pole smoothed trend filter. Entries trigger when price crosses the smoothed trend line and confirms above or below a short-

Strategy v5 TrendBreakout Repaints
Updated 2 years ago · None stated GitHub repository of SOL 1m - Strategy Candle Bar

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