Bentrix Docs
HomePricingDashboard

Donchian Channels

Trend & channelsoverlay3 linesin every package

The highest high and the lowest low of the last N bars, with their midpoint between them.

It measures the full range the market traded in over the window, shadows included. The edges move only when an extreme enters or leaves the window, so they stand flat for long stretches and then step. Readings: a close at or beyond an edge, which is a new N-bar extreme, and the channel's width.

01The study, live

Live figureScroll to zoom, drag the bars to pan.
bar —O — H — L — C —middle band —band —band —first value at —
Show where:

Computed by Bentrix’s own code over the same synthetic bars on every page — an illustration of how the study behaves, not a market.

What this figure shows

The figure is computed over 300 sample bars. Donchian Channels has no value on the first 19 — the bars it needs before it can answer — and its first value stands on bar 20. Counting the conditions the study declares on these bars: price reaches the highest never; price reaches the lowest never; price crosses above the middle line 8 times; price crosses below the middle line 8 times. Press a condition under the figure to see each place marked.

02Its parts, named

Warm-upno value on the first 19 bars: thestudy needs them before it cananswerThe upper banda set distance above the middleThe middlean average of price: the band'scentreThe lower bandthe same distance below the middleThe bars it readseach bar's open, high, low and close
Computed by Bentrix’s own code over the sample bars. It is drawn on once, as you reach the figure.

03What you see

The highest high and lowest low of the last N bars, drawn as a channel, with their midpoint.

Donchian is three lines drawn over the candles. The upper and the lower one move in flat steps and enclose every bar of the window; the middle one is halfway between them. No bar's high or low is ever outside the channel, because the window includes the bar itself.

04Where it comes from

Associated with Richard Donchian, a pioneer of trend-following funds from the late 1940s on. A channel breakout of 20 and 55 days was the entry rule of the Turtle traders of the 1980s, as Curtis Faith later described.

05The formula

Uppert=max(Ht−N+1..t),Lowert=min(Lt−N+1..t),Mid=Upper+Lower2
Ht−N+1..t, Lt−N+1..tthe highs and the lows of the last N bars
Nthe period, in bars

06A worked example

The sample bars used here are eight: closes 20, 21, 23, 22, 24, 25, 24, 26; highs 21, 22, 24, 24, 25, 26, 26, 27; lows 18, 19, 20, 21, 21, 23, 23, 23; opens 19, 20, 21, 23, 22, 24, 25, 24.

Take a period of 4 and the last four bars: highs 25, 26, 26, 27 and lows 21, 23, 23, 23.

  • upper = the highest high = 27
  • lower = the lowest low = 21
  • middle = (27 + 21) / 2 = 24.0

The upper line is touching the newest bar's own high. That is the usual convention and the reason Donchian's breakout rule compares price with the channel of the previous N bars: against a channel that includes the current bar, price can touch the line but never pass it.

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.

THE SCRIPT’S GRAPH
//@version=6
indicator("Donchian Channels", overlay = true)
length = input.int(20, "Length")
upper = ta.highest(high, length)
lower = ta.lowest(low, length)
middle = (upper + lower) / 2
plot(middle, "Middle")
plot(upper, "Upper")
plot(lower, "Lower")

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

A new high above the channel is read as price exceeding every high of the window — the classic breakout definition.

A flat channel is read as no new extremes for a while: a range.

How a new N-bar high fails. It is the oldest breakout definition there is. Most N-bar highs in a range are followed by a return into the range; the rule's reputation rests on the few that are not.

How the flat lines fail. A flat edge means no bar has exceeded it for a while; it is read as support or resistance, and it moves the moment the bar that set it leaves the window — with nothing happening in the market.

09In different markets and timeframes

Donchian channels are the highest high and lowest low of the window: the definition of a breakout. They suit markets that trend after breaking out and cost repeatedly in those that do not.

In a trend the line on the trend's side steps forward every few bars while the other stays flat far behind and moves only as old extremes leave the window. In a range both lines are flat and price travels between them. The window is a count of bars: 20 is a month of daily bars, the span Donchian used, and twenty minutes on M1, where a new 20-bar high is an everyday event. The lines are made of highs and lows, so a single spike sets one of them for the whole window.

10With other studies

Read with a second, shorter channel for exits (the Turtle rules used 20 with 10 and 55 with 20) and with the ATR for sizing.

11What it does not tell you

!

A breakout is a description: price went further than in the last N bars. Many breakouts are followed by a return into the range.

12Inputs and defaults

Donchian Channels (20, 0)settings card
1Period20
2Shift0
3TimeframeChart
4Wait for the candle to closeOn
  1. 1
    Period — 20How many bars the highest high and lowest low are taken over. Donchian's rule used four weeks (20 daily bars); the Turtle rules 20 and 55.
  2. 2
    Shift — 0Draws every line that many candles to the right (a negative number: to the left). The values are not changed, only where they stand.
  3. 3
    Timeframe — ChartThe chart's own by default; any higher one, read on the last closed candle. A finer one is never offered.
  4. 4
    Wait for the candle to close — OnThe value of a higher timeframe is taken only from a candle that has finished.

What each input changes

  • ShiftDraws all the lines that many candles to the right, or to the left with a negative number. The values do not change, only the candle each one stands on.
  • In use20 and 55 are the classic lengths.

13Limits and common misreadings

Steps. The lines change only when an extreme enters or leaves the window.

One bar sets the edge. A single spike holds a line for N bars.

14Conditions an alert or a strategy can watch

price reaches the highest eventprice is at the highest stateprice reaches the lowest eventprice is at the lowest stateprice crosses above the middle line eventprice crosses below the middle line event

Event: the bar it happens on an event happens on one barState: every bar while it holds a state holds on every bar while it lasts

These are the conditions the study itself declares — the same rules the alert editor and the strategy engine read, and the ones the figure's chips show.

15Practise it in the laboratory

Put Donchian Channels 20 on a daily chart and mark every close at a new 20-bar high over a year; count how many were followed by a further 20-bar high before a 20-bar low.

Open the laboratory

17In Bentrix

  • From the menu: a chart's Indicators button › Trend & channels › Donchian Channels, or type Donchian Channels in its search.
  • Its settings: the settings card opens when it is added; its legend's name opens it again.

18From 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": "donchian"}).

The study, as a chart files it

This is a new Donchian Channels’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": "donchian",
  "settings": {
    "period": 20,
    "shape": "period"
  }
}

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": "donchian",
      "settings": {
        "period": 20,
        "shape": "period"
      }
    }
  }
}

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": "donchian", "settings": {"period": 20, "shape": "period"}}, limit=5)
print("times:", values["times"])
for line in values["lines"]:
    print("line:", line["line"])
    print("  newest values:", line["values"])

JSJavaScript

const values = await client.study.values({ bench, symbol: market, timeframe: "H1", study: { "applied": "close", "convention": "custom", "kind": "donchian", "settings": { "period": 20, "shape": "period" } }, 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#C#

var values = await client.Study.Values(bench, market, "H1", new Dictionary<string, object?> { ["applied"] = "close", ["convention"] = "custom", ["kind"] = "donchian", ["settings"] = new Dictionary<string, object?> { ["period"] = 20, ["shape"] = "period" } }, 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"]!}");
}

GOGo

values := must(client.Study.Values(ctx, mcp.StudyValuesArgs{Bench: bench, Symbol: market, Timeframe: "H1", Study: map[string]any{"applied": "close", "convention": "custom", "kind": "donchian", "settings": map[string]any{"period": 20, "shape": "period"}}, 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", "donchian", "settings", obj("period", 20, "shape", "period"))).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++C++

auto values = client.study.values_(StudyApi::ValuesArgs(bench, market, "H1", Json::Object{{"applied", "close"}, {"convention", "custom"}, {"kind", "donchian"}, {"settings", Json::Object{{"period", 20}, {"shape", "period"}}}}).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" => "donchian", "settings" => Dict{String,Any}("period" => 20, "shape" => "period")); limit = 5)
println("times:", " ", values["times"])
for line in values["lines"]
    println("line:", " ", line["line"])
    println("  newest values:", " ", line["values"])
end

RR

values <- client$study$values(bench, market, "H1", list(applied = "close", convention = "custom", kind = "donchian", settings = list(period = 20, shape = "period")), 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")
}

RRust

let values = client.study().values(mcp::StudyValuesArgs::new(bench.clone(), market.clone(), "H1", serde_json::json!({"applied": "close", "convention": "custom", "kind": "donchian", "settings": {"period": 20, "shape": "period"}})).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 its line name and its values; values[i] belongs to the candle at times[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.
  • null is a candle with no value yet — the warm-up, about 1 × the period at the start of the history.
lineWhat it is
BandMidmiddle band
BandEdgeband
BandEdgeband

In a strategy

Filed under a key of your choice in a strategy document’s studies — here donchian: {"donchian": {"applied": "close", "convention": "custom", "kind": "donchian", "settings": {"period": 20, "shape": "period"}}} — its rules can name:

WriteWhat it is
donchian.band_midthis line, as a value in a compare
{"cond": "donchian:edge.reaches_upper"}a condition it declares itself
{"cond": "donchian:edge.at_upper"}a condition it declares itself
{"cond": "donchian:edge.reaches_lower"}a condition it declares itself
{"cond": "donchian:edge.at_lower"}a condition it declares itself
{"cond": "donchian:band.mid_cross_up"}a condition it declares itself
{"cond": "donchian:band.mid_cross_down"}a condition it declares itself

Its lines named band_edge are more than one line of that name, so a strategy reaches them through the conditions above rather than by name.

19Sources

  1. Kirkpatrick, Charles D. & Dahlquist, Julie R. Technical Analysis: The Complete Resource for Financial Market Technicians, 2nd ed. FT Press, 2010.
  2. Faith, Curtis M. Way of the Turtle. McGraw-Hill, 2007.

Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed