ZigZag
A line joining swing highs and lows that are at least the deviation per cent apart and at least the depth in bars from each other.
It measures the swings price has made, leaving out moves smaller than the deviation. A swing point is confirmed only after price has turned back by the deviation, so the last leg, from the last confirmed point to the newest extreme, is drawn dashed: it moves as price moves and is redrawn when a point is confirmed. Read as a record of past swings; no other indicator can be computed on it.
01The study, live
Computed by Bentrix’s own code over the same synthetic bars on every page — an illustration of how the study behaves, not a market. Drawn with a deviation of 0.3 % so that swings appear on these sample bars; the application’s default is 5 %.
What this figure shows
The figure is computed over 300 sample bars. ZigZag has no value on the first 2 — the bars it needs before it can answer — and its first value stands on bar 3.
02Its parts, named
03What you see
Straight lines joining swing highs and lows, ignoring any move smaller than a set percentage.
ZigZag is drawn over the candles in two parts: the confirmed legs, which run from one turning point to the next and do not change once drawn, and a last leg, drawn as provisional, from the newest confirmed turn to the extreme reached since. That last leg moves with every new extreme until price has come back by the set percentage.
04Where it comes from
The zigzag is a filter, not a measurement: it joins swing highs and lows and ignores every move smaller than a set size. Arthur Merrill used filtered waves of this kind in the 1970s to classify chart patterns.
05The formula
Step 1 — the leg in force keeps its extreme. While the leg rises, its extreme is the highest high since it began; while it falls, the lowest low:
Eₜ = max (E_(t−1), Hₜ) in a rising leg, Eₜ = min (E_(t−1), Lₜ) in a falling leg
Step 2 — the leg turns when price comes back from the extreme by the deviation, at least the depth in bars after the extreme was made:
a rising leg turns down at t: Lₜ ≤ E_(t−1)(1 − d/100) and t − t_E ≥ m
a falling leg turns up at t: Hₜ ≥ E_(t−1)(1 + d/100) and t − t_E ≥ m
Step 3 — the turn confirms a swing point. The extreme the old leg ended on becomes a confirmed swing point and is joined to the one before it; the new leg's extreme starts at this bar's low (after a turn down) or high (after a turn up).
A new swing is confirmed when price reverses by at least the deviation (in percent) from the last extreme, with at least the depth in bars between two swing points. The last leg stays provisional until the next swing confirms it.
06A worked example
Take a deviation of 5 %. The last confirmed low is 100.00, and price has since risen to a high of 108.00.
For the rise to be replaced by a new down leg, price has to fall 5 % from the high: below 108.00 × 0.95 = 102.60.
- Price dips to 103.50 and recovers to 109.00: no new leg; the high simply moves to 109.00, and the threshold to 109.00 × 0.95 = 103.55.
- Price then falls to 103.00: below the threshold. The high at 109.00 is confirmed as a pivot, and a down leg is drawn from it.
The pivot at 109.00 was confirmed only when price was at 103.00 — six points and several bars later. Until then the last leg was provisional and its end moved with every new high.
07Built in Assay
The same study written in Assay, Bentrix’s script language, and drawn by Bentrix itself as the script’s graph: each block is one step of the formula. On the ladder the steps stand in the script’s order, one a row; on the board each wire carries a value from the block that gives it to the block that reads it, left to right. The script computes exactly what the study computes — Bentrix checks the two against each other, candle by candle.
//@version=6 indicator("ZigZag", overlay = true) deviation = input.float(5.0, "Deviation %") depth = input.int(10, "Depth") // TA-Lib's ZIGZAG: the extreme of the leg in force, which way that leg runs, and the bar the extreme stands on. // A leg turns once price comes back `deviation` per cent from its extreme, at least `depth` bars on. [extreme, direction, pivotBar] = talib.ZIGZAG(deviation, depth) // When the leg turns, the extreme it ended on is confirmed as a pivot and joined to the pivot before it. var int lastBar = na var float lastPrice = na turned = not na(direction[1]) and direction != direction[1] if turned if not na(lastBar) line.new(lastBar, lastPrice, pivotBar[1], extreme[1], color = color.blue, width = 2) lastBar := pivotBar[1] lastPrice := extreme[1] // The leg still forming, from the last pivot to the newest extreme; it redraws itself as price moves. var line forming = na if not na(lastBar) and barstate.islast forming := line.new(lastBar, lastPrice, pivotBar, extreme, color = color.gray, style = line.style_dashed) plot(extreme, "Leg extreme", display = display.none)
Paste it into the Assay IDE to put it on a chart, or to change it. Looking at the graph is free in every package; editing it as blocks is Plus.
08Readings — what traders look for
The zigzag is used to see a market's structure — higher highs and higher lows, or lower ones — and to measure swings, for example for Fibonacci retracements.
How the swings fail as a live reading. On history the zigzag marks every turn at its exact bar. Live, the last leg is unconfirmed: its end moves until price has reversed by the full deviation. The perfect tops and bottoms on the left of the chart were all drawn in hindsight.
09In different markets and timeframes
A zigzag filters out moves smaller than a threshold to show the swings; its last leg moves until confirmed. It is a tool for studying past structure, on any timeframe.
10With other studies
Read beside Fractals (another marker of swing points) and used to measure swings for Fibonacci and pattern work.
11What it does not tell you
It repaints. The last leg moves until a reversal confirms it, so on a historical chart the zigzag looks perfect and live it does not. It describes swings after the fact. See repaintRepaintAn indicator repaints when its past values change as new bars arrive — it looks perfect on history and behaves differently live..
12Inputs and defaults
- 1Depth — 10The fewest bars a pivot must stand apart from the last, so that two pivots are not drawn on neighbouring bars.
- 2Deviation (%) — 5The smallest reversal, in per cent, that ends a leg. Larger: fewer, bigger swings.
The settings in use
- In use5 % and 10 bars by default; the percentage has to suit the instrument — 5 % is large for a currency pair.
13Limits and common misreadings
The last leg repaints. It is redrawn until the reversal that confirms it.
A percentage, not volatility: 5 % is a large move in one market and noise in another.
14Practise it in the laboratory
Step a replay forward bar by bar with the ZigZag on and watch its last leg change.
Open the laboratory16In Bentrix
- From the menu: a chart's Indicators button › Trend & channels › ZigZag, or type ZigZag in its search.
- Its settings: the settings card opens when it is added; its legend's name opens it again.
17From an agent or a program
Two tools reach it. study_values computes it over a workbench’s candles up to the clock — no chart needed — and study_attach puts it on a chart, where it is drawn and saved with the chart ({"chart": "<chart uri>", "kind": "zigzag"}).
The study, as a chart files it
This is a new ZigZag’s entry — its kind, its calculation, the price it reads and its settings. Change a setting here to read it with other inputs.
{
"applied": "close",
"convention": "custom",
"kind": "zigzag",
"settings": {
"depth": 10,
"deviation_pct": 5.0,
"shape": "zigzag"
}
}An agent
An agent calls the MCP tool with it:
{
"name": "study_values",
"arguments": {
"bench": "bentrix://lab/\u2026/bench/\u2026",
"symbol": "EURUSD",
"timeframe": "H1",
"limit": 5,
"study": {
"applied": "close",
"convention": "custom",
"kind": "zigzag",
"settings": {
"depth": 10,
"deviation_pct": 5.0,
"shape": "zigzag"
}
}
}
}A program
A program does the same in its language — bench and market as in the built-in indicators guide:
Python
values = client.study.values(bench, market, "H1", {"applied": "close", "convention": "custom", "kind": "zigzag", "settings": {"depth": 10, "deviation_pct": 5.0, "shape": "zigzag"}}, limit=5)
print("times:", values["times"])
for line in values["lines"]:
print("line:", line["line"])
print(" newest values:", line["values"])JavaScript
const values = await client.study.values({ bench, symbol: market, timeframe: "H1", study: { "applied": "close", "convention": "custom", "kind": "zigzag", "settings": { "depth": 10, "deviation_pct": 5.0, "shape": "zigzag" } }, limit: 5 });
console.log("times:", values.times);
for (const line of values.lines) {
console.log("line:", line.line);
console.log(" newest values:", line.values);
}C#
var values = await client.Study.Values(bench, market, "H1", new Dictionary<string, object?> { ["applied"] = "close", ["convention"] = "custom", ["kind"] = "zigzag", ["settings"] = new Dictionary<string, object?> { ["depth"] = 10, ["deviation_pct"] = 5.0, ["shape"] = "zigzag" } }, limit: 5);
Console.WriteLine($"times: {values!["times"]!}");
foreach (var line in values!["lines"]!.AsArray())
{
Console.WriteLine($"line: {line!["line"]!}");
Console.WriteLine($" newest values: {line!["values"]!}");
}Go
values := must(client.Study.Values(ctx, mcp.StudyValuesArgs{Bench: bench, Symbol: market, Timeframe: "H1", Study: map[string]any{"applied": "close", "convention": "custom", "kind": "zigzag", "settings": map[string]any{"depth": 10, "deviation_pct": 5.0, "shape": "zigzag"}}, Limit: mcp.Ptr[int64](5)}))
fmt.Println("times:", at(values, "times"))
for _, line := range at(values, "lines").([]any) {
fmt.Println("line:", at(line, "line"))
fmt.Println(" newest values:", at(line, "values"))
}Java
Object values = client.study.values(new Bentrix.StudyApi.ValuesArgs(bench, market, "H1", obj("applied", "close", "convention", "custom", "kind", "zigzag", "settings", obj("depth", 10, "deviation_pct", 5.0, "shape", "zigzag"))).limit(5L));
System.out.println("times:" + " " + at(values, "times"));
for (Object line : (List<Object>) at(values, "lines")) {
System.out.println("line:" + " " + at(line, "line"));
System.out.println(" newest values:" + " " + at(line, "values"));
}C++
auto values = client.study.values_(StudyApi::ValuesArgs(bench, market, "H1", Json::Object{{"applied", "close"}, {"convention", "custom"}, {"kind", "zigzag"}, {"settings", Json::Object{{"depth", 10}, {"deviation_pct", 5.0}, {"shape", "zigzag"}}}}).limit(5));
std::cout << "times:" << " " << values["times"].dump() << std::endl;
for (const Json &line : values["lines"].arr()) {
std::cout << "line:" << " " << line["line"].dump() << std::endl;
std::cout << " newest values:" << " " << line["values"].dump() << std::endl;
}Julia
values = client.study.values(bench, market, "H1", Dict{String,Any}("applied" => "close", "convention" => "custom", "kind" => "zigzag", "settings" => Dict{String,Any}("depth" => 10, "deviation_pct" => 5.0, "shape" => "zigzag")); limit = 5)
println("times:", " ", values["times"])
for line in values["lines"]
println("line:", " ", line["line"])
println(" newest values:", " ", line["values"])
endR
values <- client$study$values(bench, market, "H1", list(applied = "close", convention = "custom", kind = "zigzag", settings = list(depth = 10, deviation_pct = 5.0, shape = "zigzag")), limit = 5)
cat("times:", format(values$times), "\n")
for (line in values$lines) {
cat("line:", format(line$line), "\n")
cat(" newest values:", format(line$values), "\n")
}Rust
let values = client.study().values(mcp::StudyValuesArgs::new(bench.clone(), market.clone(), "H1", serde_json::json!({"applied": "close", "convention": "custom", "kind": "zigzag", "settings": {"depth": 10, "deviation_pct": 5.0, "shape": "zigzag"}})).limit(5))?;
println!("times: {}", values["times"]);
for line in values["lines"].as_array().into_iter().flatten() {
println!("line: {}", line["line"]);
println!(" newest values: {}", line["values"]);
}Reading the answer
times— the candles’ open times, in milliseconds since 1970 (UTC), oldest first.lines— one entry per line, in this order, each with itslinename and itsvalues;values[i]belongs to the candle attimes[i].- The last value is the candle at the clock’s, which may still be forming: it changes until that candle closes, as on the chart. Nothing after the clock is ever computed.
nullis a candle with no value yet — the warm-up, about 1 × the period at the start of the history.
line | What it is |
|---|---|
Main | line |
Provisional | provisional leg |
In a strategy
A strategy cannot read it: its value at a candle depends on candles after it, which a strategy never sees. The strategy document refuses it.
18Sources
- Murphy, John J. Technical Analysis of the Financial Markets. New York Institute of Finance, 1999.
Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed