Tradingbot
Pine Script v5 · FREE RESOURCE

ZigZag Optimized v2 | Confirmed Signals

A Pine Script v5 indicator combining confirmed ZigZag reversals with EMA and Supertrend filters.

ICODERX Editorialv2Updated 11/20/20260 saves

Source code

v2
//@version=5
indicator("ZigZag Optimized v2 | Confirmed Signals", shorttitle="ZZ Optimized v2", overlay=true, max_labels_count=500)

// --- Inputs ---
grpSignal = "01 | Signal filters"
zzPct       = input.float(1.0, "ZigZag reversal (%)", minval=0.1, step=0.1, group=grpSignal)
emaLen      = input.int(200, "EMA length", minval=1, group=grpSignal)
emaMinGap   = input.float(1.0, "Min price/EMA gap (%)", minval=0, step=0.1, group=grpSignal)
emaMaxGap   = input.float(5.0, "Max price/EMA gap (%)", minval=0.1, step=0.1, group=grpSignal)
atrLen      = input.int(2, "Supertrend ATR length", minval=1, group=grpSignal)
stFactor    = input.float(1.0, "Supertrend factor", minval=0.01, step=0.1, group=grpSignal)
allowLong   = input.bool(true, "Allow Long", group=grpSignal)
allowShort  = input.bool(true, "Allow Short", group=grpSignal)
flipTrade   = input.bool(false, "Invert entry direction", group=grpSignal)

// These settings are simulated exits on confirmed candle closes, not exchange stop orders.
grpRisk = "02 | Exit management"
enableSL     = input.bool(true, "Stop loss", group=grpRisk)
slPct        = input.float(4.0, "Stop loss (%)", minval=0.1, step=0.1, group=grpRisk)
enableTrail  = input.bool(true, "Trailing stop", group=grpRisk)
trailPct     = input.float(2.0, "Trailing stop (%)", minval=0.1, step=0.1, group=grpRisk)
enableTP     = input.bool(true, "Trailing take profit", group=grpRisk)
tpArmPct     = input.float(2.0, "Activate trailing TP at profit (%)", minval=0.1, step=0.1, group=grpRisk)
tpTrailPct   = input.float(1.0, "Trailing TP retracement (%)", minval=0.1, step=0.1, group=grpRisk)
enableInstant = input.bool(true, "Instant candle-based profit close", group=grpRisk)
instantPct   = input.float(1.0, "Instant minimum profit (%)", minval=0.1, step=0.1, group=grpRisk)
minRangePct  = input.float(0.5, "Minimum candle range (%)", minval=0, step=0.1, group=grpRisk)
maxBodyRatio = input.float(0.30, "Max candle body / range", minval=0.01, maxval=1, step=0.05, group=grpRisk)
closeOpposite = input.bool(true, "Close on opposite ZigZag direction", group=grpRisk)

grpView = "03 | Display & webhook"
showLevels = input.bool(true, "Show active SL / trailing levels", group=grpView)
showLabels = input.bool(true, "Show entries and exits", group=grpView)
sendAlerts = input.bool(true, "Send alert() webhook JSON", group=grpView)

// --- Indicators, evaluated on the chart's real OHLC ---
emaValue = ta.ema(close, emaLen)
[stValue, stDirection] = ta.supertrend(stFactor, atrLen)
plot(emaValue, "EMA", color=color.orange, linewidth=2)
plot(stDirection < 0 ? stValue : na, "Supertrend up", color=color.new(color.green, 15), style=plot.style_linebr)
plot(stDirection > 0 ? stValue : na, "Supertrend down", color=color.new(color.red, 15), style=plot.style_linebr)

// Causal ZigZag: tracks extremes, confirms reversals with a CLOSED bar.
// No backward offset is applied; reversal is known only at the confirmation bar.
var int zzDirection = 1
var float zzHigh = na
var float zzLow = na
if barstate.isfirst
    zzHigh := high
    zzLow := low

bool zzToLong = false
bool zzToShort = false
if barstate.isconfirmed
    if zzDirection == 1
        zzHigh := math.max(nz(zzHigh, high), high)
        if close <= zzHigh * (1.0 - zzPct / 100.0)
            zzDirection := -1
            zzLow := low
            zzToShort := true
    else
        zzLow := math.min(nz(zzLow, low), low)
        if close >= zzLow * (1.0 + zzPct / 100.0)
            zzDirection := 1
            zzHigh := high
            zzToLong := true

float emaGapPct = emaValue != 0 ? math.abs(close / emaValue - 1.0) * 100.0 : na
bool gapOK = not na(emaGapPct) and emaGapPct >= emaMinGap and emaGapPct <= emaMaxGap
bool baseLong = zzToLong and gapOK and close > emaValue and stDirection < 0
bool baseShort = zzToShort and gapOK and close < emaValue and stDirection > 0
bool wantLong = flipTrade ? baseShort : baseLong
bool wantShort = flipTrade ? baseLong : baseShort

// --- Single-position state machine ---
var int position = 0      // 0 = flat, 1 = long, -1 = short
var float entryPrice = na
var int entryBar = na
var float peak = na
var float trough = na
var bool tpArmed = false

bool openLong = false
bool openShort = false
bool closeLong = false
bool closeShort = false
string exitReason = ""

// Lock events to confirmed bars; avoid ambiguous entry-and-exit within one candle.
if barstate.isconfirmed
    if position != 0 and bar_index > entryBar
        float previousPeak = nz(peak, high)
        float previousTrough = nz(trough, low)
        float updatedPeak = math.max(previousPeak, high)
        float updatedTrough = math.min(previousTrough, low)
        // Stop levels are calculated from PREVIOUS confirmed bars so this candle's
        // high/low cannot move a trailing stop before testing the same candle.
        float fixedSL = position == 1 ? entryPrice * (1 - slPct / 100) : entryPrice * (1 + slPct / 100)
        float trailingStop = position == 1 ? previousPeak * (1 - trailPct / 100) : previousTrough * (1 + trailPct / 100)
        float tpStop = position == 1 ? previousPeak * (1 - tpTrailPct / 100) : previousTrough * (1 + tpTrailPct / 100)
        bool stopHit = enableSL and (position == 1 ? low <= fixedSL : high >= fixedSL)
        bool trailHit = enableTrail and (position == 1 ? low <= trailingStop : high >= trailingStop)
        bool tpHit = enableTP and tpArmed and (position == 1 ? low <= tpStop : high >= tpStop)
        float candleRange = high - low
        bool smallBody = candleRange > 0 and math.abs(close - open) / candleRange <= maxBodyRatio
        bool sufficientRange = low > 0 and candleRange / low * 100 >= minRangePct
        // More conservative than original: instantaneous close must ALSO be in profit at the close.
        bool instantHit = enableInstant and smallBody and sufficientRange and (position == 1 ? close >= entryPrice * (1 + instantPct / 100) : close <= entryPrice * (1 - instantPct / 100))
        bool oppositeHit = closeOpposite and (position == 1 ? zzToShort : zzToLong)

        // Conservative priority for OHLC ambiguity: SL > trailing stop > TP > instant > opposite.
        exitReason := stopHit ? "SL" : trailHit ? "TRAIL" : tpHit ? "TP_TRAIL" : instantHit ? "INSTANT" : oppositeHit ? "OPPOSITE" : ""
        if exitReason != ""
            closeLong := position == 1
            closeShort := position == -1
            position := 0
            entryPrice := na
            entryBar := na
            peak := na
            trough := na
            tpArmed := false
        else
            peak := updatedPeak
            trough := updatedTrough
            tpArmed := tpArmed or (enableTP and (position == 1 ? peak >= entryPrice * (1 + tpArmPct / 100) : trough <= entryPrice * (1 - tpArmPct / 100)))

    // Only one event can occur per bar. After a close, wait for the next distinct entry signal.
    if position == 0 and not closeLong and not closeShort
        if wantLong and allowLong
            position := 1
            entryPrice := close
            entryBar := bar_index
            peak := high
            trough := low
            tpArmed := false
            openLong := true
        else if wantShort and allowShort
            position := -1
            entryPrice := close
            entryBar := bar_index
            peak := high
            trough := low
            tpArmed := false
            openShort := true

float activeSL = position == 0 or not enableSL ? na : position == 1 ? entryPrice * (1 - slPct / 100) : entryPrice * (1 + slPct / 100)
float activeTrail = position == 0 or not enableTrail ? na : position == 1 ? peak * (1 - trailPct / 100) : trough * (1 + trailPct / 100)
float activeTP = position == 0 or not enableTP or not tpArmed ? na : position == 1 ? peak * (1 - tpTrailPct / 100) : trough * (1 + tpTrailPct / 100)
plot(showLevels ? activeSL : na, "Active SL", color=color.red, style=plot.style_linebr, linewidth=2)
plot(showLevels ? activeTrail : na, "Active Trailing Stop", color=color.fuchsia, style=plot.style_linebr)
plot(showLevels ? activeTP : na, "Active Trailing TP", color=color.lime, style=plot.style_linebr)
plotshape(showLabels and openLong, "Open Long", shape.triangleup, location.belowbar, color.lime, size=size.small, text="LONG")
plotshape(showLabels and openShort, "Open Short", shape.triangledown, location.abovebar, color.red, size=size.small, text="SHORT")
plotshape(showLabels and closeLong, "Close Long", shape.labeldown, location.abovebar, color.orange, size=size.tiny, text="CLOSE L")
plotshape(showLabels and closeShort, "Close Short", shape.labelup, location.belowbar, color.orange, size=size.tiny, text="CLOSE S")

// --- Structured webhook: exactly one event on a confirmed bar ---
string eventName = openLong ? "Open Longs By ZigZag" : openShort ? "Open Shorts By ZigZag" : closeLong ? "Close Longs By ZigZag" : closeShort ? "Close Shorts By ZigZag" : ""
if sendAlerts and barstate.isconfirmed and eventName != ""
    string reasonField = closeLong or closeShort ? exitReason : "ENTRY"
    string payload = '{"alert":"' + eventName + '","reason":"' + reasonField + '","ticker":"' + syminfo.ticker + '","tf":"' + timeframe.period + '","ohlcv":{"open":' + str.tostring(open) + ',"high":' + str.tostring(high) + ',"low":' + str.tostring(low) + ',"close":' + str.tostring(close) + ',"volume":' + str.tostring(nz(volume, 0)) + '},"bartime":' + str.tostring(time) + '}'
    alert(payload, alert.freq_once_per_bar_close)

alertcondition(openLong, "Long entry", "Confirmed Long entry")
alertcondition(openShort, "Short entry", "Confirmed Short entry")
alertcondition(closeLong, "Long exit", "Confirmed Long exit")
alertcondition(closeShort, "Short exit", "Confirmed Short exit")
1 files · Read-only · Unspecified · Source is not executed here

How it works

ZigZag tracks highs or lows and confirms reversals at candle close. EMA distance and Supertrend direction filter the signals. Entry and exit markers describe the indicator’s simulated position state.

Install

  1. Download or copy the complete Pine Script file.
  2. Paste it into TradingView’s Pine Editor, save it and select Add to chart.
  3. Review ZigZag, EMA, Supertrend and exit settings across several market conditions.

Alerts and limitations

The indicator can emit JSON alerts at candle close in TradingView. Stop loss, trailing stop and take profit are simulated OHLC rules and do not send orders to an exchange.

Source

The project owner supplied the original file for free sharing. The file includes no reuse license text.

Educational content, not investment advice. Trading can result in capital loss. No profit is guaranteed.

Join the discussion