Hilbert Transform, Trend vs Cycle Mode (HT Trend vs Cycle)
Hilbert Transform Trend versus Cycle Mode — 1 when the transform's own tests call the market trending, 0 when it calls it cycling.
It measures a regime classification, and it is a binary output rather than a strength. The conventional use is as a switch between trend-following and mean-reverting readings; no accuracy is claimed for that classification.
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.
What this figure shows
The figure is computed over 300 sample bars. HT Trend vs Cycle has no value on the first 63 — the bars it needs before it can answer — and its first value stands on bar 64. Its bars run between 0 and 1 on these bars, and the last value is 0. The pane's scale is fixed at 0 to 1, the range the study can take. Counting the conditions the study declares on these bars: switches to trend mode 7 times; switches to cycle mode 8 times. Press a condition under the figure to see each place marked. As states rather than moments: is in trend mode on 160 bars; is in cycle mode on 77 bars.
02Its parts, named
03What you see
1 in trend mode, 0 in cycle mode.
A step line in its own pane that reads either 1 or 0: 1 where the transform's tests call the market trending, 0 where they call it cycling.
04Where it comes from
John Ehlers adapted the Hilbert transform from signal processing in Rocket Science for Traders (2001); TA-Lib implements his formulas.
05The formula
Step 1 — the price is smoothed over four bars:
sₜ = (4Pₜ + 3P_(t−1) + 2P_(t−2) + P_(t−3))/10
Step 2 — the Hilbert transform is a fixed filter over seven bars, scaled by the period measured on the bar before:
HT(x)ₜ = cₜ(0.0962 xₜ + 0.5769 x_(t−2) − 0.5769 x_(t−4) − 0.0962 x_(t−6)), cₜ = 0.075 T_(t−1) + 0.54
Step 3 — the two components. The detrended price, delayed three bars, is the in-phase component; its transform is the quadrature:
Dₜ = HT(s)ₜ, Iₜ = D_(t−3), Qₜ = HT(D)ₜ
Step 4 — the period. The components are advanced a quarter turn against each other, each result smoothed (a fifth of the new value, four fifths of the old), and the angle between one bar and the next gives the period:
I'ₜ = Iₜ − HT(Q)ₜ, Q'ₜ = Qₜ + HT(I)ₜ
Reₜ = 0.2(I'ₜ I'_(t−1) + Q'ₜ Q'_(t−1)) + 0.8 Re_(t−1), Imₜ = 0.2(I'ₜ Q'_(t−1) − Q'ₜ I'_(t−1)) + 0.8 Im_(t−1)
Tₜ = 360/(arctan (Imₜ / Reₜ)), Periodₜ = 0.33 Tₜ + 0.67 Period_(t−1)
Step 5 — the phase. With the period rounded to whole bars, the smoothed price of the last bars is set against one turn of a sine and a cosine:
Aₜ = Σ[i=0..n−1] sin ((360 i)/n) s_(t−i), Bₜ = Σ[i=0..n−1] cos ((360 i)/n) s_(t−i)
φₜ = arctan (Aₜ/Bₜ) + 90 + 360/Periodₜ
Step 6 — the two sines of the phase:
Sineₜ = sin (φₜ), LeadSineₜ = sin (φₜ + 45)
Step 7 — the trendline. The price itself is averaged over one cycle, and the last four averages are weighted:
mₜ = 1/n Σ[i=0..n−1] P_(t−i), Trendlineₜ = (4mₜ + 3m_(t−1) + 2m_(t−2) + m_(t−3))/10
Step 8 — the mode. Three tests, the last one deciding:
Modeₜ = { 1 if |(sₜ − Trendlineₜ)/Trendlineₜ| ≥ 0.015; 0 if the two sines crossed fewer than 1/2 · Periodₜ bars ago; 0 if 0.67 · 360/Periodₜ < φₜ − φ_(t−1) < 1.5 · 360/Periodₜ; 1 otherwise }In words: The Hilbert transform produces, from the detrended price, a quadrature component 90° out of phase with it. From the in-phase and quadrature components come the phase, its rate of change (the period), and the rest. The calculations are long; TA-Lib's implementation is the one computed here.
The Trend Mode is the last step: a set of tests on those measurements — how lately the sine waves crossed, whether the phase advances at the cycle's rate, how far price stands from the Hilbert trendline — answered as 1 (trend) or 0 (cycle).
06A worked example
The answer comes from several tests on the Hilbert outputs; the market is called cycling (0) only while they all agree. Three of them, for one bar:
- Have the sine waves crossed recently? Each crossing of sine and lead sine starts a count; within half a dominant cycle of a crossing, the mode is cycle. With a 20-bar cycle that is 10 bars.
- Is the phase advancing at the cycle's rate? A 20-bar cycle should advance 18° per bar; an advance between about two thirds and one and a half times that (12°–27°) is consistent with a cycle.
- Is price far from the trendline? If the smoothed price is more than 1.5 % away from the Hilbert trendline, the mode is trend, whatever the other tests say.
So with the last crossing 14 bars ago, the answer is 1 (trend) on the first test alone.
Computed by Bentrix on a known wave: on Bentrix's hundred-bar sample wave — closes of 100 + 0.05 i + 2 sin(2π i / 20) for bars i = 0 to 99, a 20-bar wave two points high on a slow rise, each bar opening at the close before, its high and low half a point beyond its body — the mode reads 0 (cycle) on the last bar. The wave is regular and two points high, and the rise beneath it only a twentieth of a point a bar, so every test finds a cycle.
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("Hilbert Transform, Trend versus Cycle Mode") // 1 where the transform's tests call the market trending, 0 where cycling. value = talib.HT_TRENDMODE(close) plot(value, "Trend mode")
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
Trend mode 1 is read as the cycle measurement having lost its regularity — the market trending.
As a switch. The conventional use is to choose between two kinds of reading: trend-following studies while it reads 1, oscillators while it reads 0. It fails by lag and by flicker: the classification is made from smoothed, delayed measurements, so it changes after the market has, and near the thresholds it flips back and forth.
09In different markets and timeframes
The trend mode is a 0 or 1 judgement made from delayed measurements; it changes after the market has, and flickers near its thresholds.
It needs some 63 bars before its first answer and judges from a cycle measured over the recent dozens of bars, so on any timeframe it describes a stretch that is already behind the current bar. In a long, clean trend it reads 1 for most of the move; in a market that swings regularly it reads 0; in the common case between the two it switches back and forth. A switch on M1 follows a few minutes of evidence; on D1, weeks. The thresholds inside it are fixed numbers from Ehlers' design and are the same for every market.
10With other studies
Used as a switch between trend-following and oscillator readings; read beside the ADX for a second opinion.
11What it does not tell you
A measured cycle is a description of the recent window; markets are not obliged to keep a rhythm, and the measures need a long warm-up.
12Inputs and defaults
- 1Applied price — CloseAny of the seven prices, and several at once, each its own line with its own look.
- 2Timeframe — ChartThe chart's own by default; any higher one, read on the last closed candle. A finer one is never offered.
- 3Wait for the candle to close — OnThe value of a higher timeframe is taken only from a candle that has finished.
What each input changes
- TimeframeThe study has no numeric input.
- In useIt has no input.
13Limits and common misreadings
Long warm-up. TA-Lib's Hilbert studies give no value for the first 63 bars (32 for some), and their recursion needs longer still to settle.
Binary. It says nothing about how strong a trend or how clean a cycle is.
Thresholds are fixed constants from Ehlers' design, not fitted to any market.
14Conditions an alert or a strategy can watch
an event happens on one bar 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 the trend mode under a chart and shade, by eye, where the market trended; compare the shading with where the line read 1.
Open the laboratory17In Bentrix
- From the menu: a chart's Indicators button › Cycle › HT Trend vs Cycle, or type HT Trend vs Cycle 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": "ht_trend_mode"}).
The study, as a chart files it
This is a new HT Trend vs Cycle’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": "talib",
"kind": "ht_trend_mode",
"settings": {
"shape": "none"
}
}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": "talib",
"kind": "ht_trend_mode",
"settings": {
"shape": "none"
}
}
}
}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": "talib", "kind": "ht_trend_mode", "settings": {"shape": "none"}}, 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": "talib", "kind": "ht_trend_mode", "settings": { "shape": "none" } }, 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"] = "talib", ["kind"] = "ht_trend_mode", ["settings"] = new Dictionary<string, object?> { ["shape"] = "none" } }, 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": "talib", "kind": "ht_trend_mode", "settings": map[string]any{"shape": "none"}}, 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", "talib", "kind", "ht_trend_mode", "settings", obj("shape", "none"))).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", "talib"}, {"kind", "ht_trend_mode"}, {"settings", Json::Object{{"shape", "none"}}}}).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" => "talib", "kind" => "ht_trend_mode", "settings" => Dict{String,Any}("shape" => "none")); 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 = "talib", kind = "ht_trend_mode", settings = list(shape = "none")), 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": "talib", "kind": "ht_trend_mode", "settings": {"shape": "none"}})).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 | the indicator's own value |
In a strategy
Filed under a key of your choice in a strategy document’s studies — here ht_trend_mode: {"ht_trend_mode": {"applied": "close", "convention": "talib", "kind": "ht_trend_mode", "settings": {"shape": "none"}}} — its rules can name:
| Write | What it is |
|---|---|
ht_trend_mode | its main line, as a value in a compare |
{"cond": "ht_trend_mode:mode.to_one"} | a condition it declares itself |
{"cond": "ht_trend_mode:mode.to_zero"} | a condition it declares itself |
{"cond": "ht_trend_mode:mode.is_one"} | a condition it declares itself |
{"cond": "ht_trend_mode:mode.is_zero"} | a condition it declares itself |
19Sources
- Ehlers, John F. Rocket Science for Traders. Wiley, 2001.
Bentrix 0.1.382Every number, name and default on these pages is read from the application itself.What is comingWhat changed