Appearance
Zig Zag
Joins swing highs and lows that reverse by more than a set percentage.
Kind indicator · Drawn on the price pane
Try it
On the chart, press / and choose Zig Zag under Support & resistance. To change it, copy the source below into the AlphaScript editor.
Inputs
| Input | Type | Default |
|---|---|---|
| Price deviation for reversals (%) | float | 5 |
| Show price labels | bool | true |
| Line color | color | "#2962FF" |
| Line width | int | 2 |
Source
From packages/alphascript/indicators/zigzag.as.js.
js
indicator({ name: "Zig Zag", shortTitle: "ZigZag", overlay: true });
const deviation = input.float("Price deviation for reversals (%)", 5, { min: 0.01, step: 0.5 });
const showLabels = input.bool("Show price labels", true);
const color = input.color("Line color", "#2962FF", { group: "Style" });
const width = input.int("Line width", 2, { min: 1, max: 4 });
/** @param {number} p */
const fmt = (p) => { const d = p > 0 ? math.max(2, 4 - math.floor(math.log(p) / math.log(10))) : 2; return String(math.round(p, d)); };
let dir = 0, anchorT = NaN, anchorP = NaN, extT = NaN, extP = NaN, line = 0, prevPivot = NaN;
event.onCandle((bar) => {
if (dir === 0) {
anchorT = extT = bar.time; anchorP = bar.low; extP = bar.high; dir = 1;
line = draw.line({ x1: anchorT, y1: anchorP, x2: extT, y2: extP, color, width });
return;
}
if (dir === 1 ? bar.high >= extP : bar.low <= extP) {
extT = bar.time; extP = dir === 1 ? bar.high : bar.low;
draw.set(line, { x2: extT, y2: extP });
return;
}
const back = dir === 1 ? bar.low : bar.high;
if (math.abs(back - extP) / extP * 100 < deviation) return;
if (showLabels) {
const pct = prevPivot === prevPivot ? ((extP - prevPivot) / prevPivot) * 100 : NaN;
draw.label({ x: extT, y: extP, text: pct === pct ? `${fmt(extP)} (${pct >= 0 ? "+" : ""}${math.round(pct, 2)}%)` : fmt(extP),
style: dir === 1 ? "down" : "up", color: "rgba(0,0,0,0)", textColor: color, size: "small" });
}
prevPivot = extP;
anchorT = extT; anchorP = extP; dir = -dir; extT = bar.time; extP = back;
line = draw.line({ x1: anchorT, y1: anchorP, x2: extT, y2: extP, color, width });
});