Bentrix Docs
HomePricingDashboard

Exponential Moving Average EMA

Moving averagesoverlayone linein every package

A recursive average that weights the newest value most and lets older ones decay geometrically, so it turns sooner than an SMA of the same length.

It measures the same centre with less lag and more sensitivity to the last few bars. Read as trend direction, as a level price returns to, and through crossings. The two conventions differ at the start: MT5 seeds from the first bar and has a value everywhere; TA-Lib seeds with the SMA of the first N values and reports nothing for the first N−1 bars. The two lines begin apart and converge: the gap shrinks by the factor (N−1)/ (N+1) every bar, so after a few multiples of N it is too small to see.

01The study, live

Live figureScroll to zoom, drag the bars to pan.
bar —O — H — L — C —EMA —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. EMA has no value on the first 49 — the bars it needs before it can answer — and its first value stands on bar 50. Of the 251 bars that have a value, the close is above the line on 125 and below it on 126. Counting the conditions the study declares on these bars: price crosses above the line 3 times; price crosses below the line 3 times. Press a condition under the figure to see each place marked. As states rather than moments: price is above the line on 125 bars; price is below the line on 126 bars.

02Its parts, named

Warm-upno value on the first 49 bars: thestudy needs them before it cananswerThe bars it readseach bar's close, unless you chooseanother priceThe linethe study's value, one for each bar
Computed by Bentrix’s own code over the sample bars. It is drawn on once, as you reach the figure.

03What you see

A line like the SMA, but closer to price: it turns sooner after price turns, because the newest bars weigh more than the older ones.

04Where it comes from

Exponential smoothing was developed in operations research in the 1950s and 1960s — Robert G. Brown's work on forecasting inventory demand is the classic account — and passed into trading as a moving average that reacts faster than the simple one without discarding the past abruptly. It is the building block of MACD, of DEMA and TEMA, and of many others.

05The formula

EMAt=αPt+(1−α)EMAt−1,α=2N+1
Ptthe price of this bar
Nthe period
αthe share the newest price takes

Every past price still counts, with a weight that shrinks by the factor (1−α) each bar. With N=9, α=0.2: the newest close counts 20 %, the one before 16 %, then 12.8 %, and so on.

20%16%12.8%10.2%8.2%6.6%5.2%4.2%3.4%
1

The first value has to come from somewhere. Bentrix offers two conventions: TA-Lib (the default) seeds the EMA with the SMA of the first N prices; MetaTrader 5 seeds it with the first price. The two agree after the warm-up and differ at the start.

06A worked example

Take eight closes — 20, 21, 23, 22, 24, 25, 24, 26 — and a period of 3, so α = 2 / (3 + 1) = 0.5.

With the TA-Lib convention the first value is the simple average of the first three closes: (20 + 21 + 23) / 3 = 21.33. From then on each bar takes half of the new close and half of the previous value:

  • bar 4: 0.5 × 22 + 0.5 × 21.33 = 21.67
  • bar 5: 0.5 × 24 + 0.5 × 21.67 = 22.83
  • bar 6: 0.5 × 25 + 0.5 × 22.83 = 23.92

and so on to 24.98 on the last bar. The simple average of the same period ends at 25.00: the EMA is nearer the last close (26) because that close alone carries half the weight.

With the MetaTrader 5 convention the first value is the first close itself (20), and the same recursion runs from the second bar: 20.50, 21.75, 21.88, … By the eighth bar the two conventions read 24.98 and 24.99 — already within a few hundredths of each other.

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("Exponential Moving Average", overlay = true)
length = input.int(50, "Length")
// Each bar takes this share of the newest close, and keeps the rest of the line.
alpha = 2.0 / (length + 1)
// The first value is the simple average of the first `length` closes.
var float ema = na
ema := na(ema[1]) ? ta.sma(close, length) : alpha * close + (1 - alpha) * ema[1]
plot(ema, "EMA")

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

Price against the line, the slope and two averages crossing are read as with the SMA, but the EMA reaches each event sooner.

Short EMAs as a trend guide. Many traders watch whether pullbacks stay above a short EMA (8, 9, 21) during a move, reading a close beyond it as the pullback having become deeper than recent ones.

The 12/26 pair is MACD's: the gap between them is what MACD draws.

Price against the line, and when that fails. Because the EMA follows price more closely than the SMA, price touches and crosses it more often. In a sideways market price crosses any average again and again, and each crossing looks the same as the one that begins a trend; the average cannot tell them apart until afterwards.

The slope. A rising EMA says the newest closes are above the weighted past. It turns sooner than an SMA of the same period, and for the same reason turns back sooner too: a two-bar pullback in a strong move can flatten a short EMA without the move having ended.

09In different markets and timeframes

The exponential average suits markets that turn quickly, where the simple average's equal weighting keeps reporting the old move. It pays for that in ranges, where its quicker turns are mostly noise. On higher timeframes the difference from an SMA of the same period shrinks relative to the bars; on one-minute charts it is plain to the eye. On Renko and other price-built charts both averages are smooth and the EMA's lead is small.

10With other studies

Read in pairs (12 and 26 are MACD's; 9 and 21 a common short pair), where the gap between the two is itself the MACD line; beside the Keltner Channel, whose middle is an EMA; and as the reference for Elder's Bulls and Bears Power, which measure how far a bar's high and low stand from it.

11What it does not tell you

!

Reacting sooner also means reacting to noise: an EMA turns on moves that the SMA would have ignored, and some of those moves go nowhere. Faster is not more accurate; it is a different trade-off between lag and false turns.

12Inputs and defaults

EMA (50, 0)settings card
1Period50
2Shift0
3Applied priceClose
4TimeframeChart
5CalculationTA-Lib
6Wait for the candle to closeOn
  1. 1
    Period — 50The number of bars in the window. A longer period gives a smoother line that turns later; a shorter one hugs price and turns on smaller moves. Doubling the period roughly doubles the lag.
  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
    Applied price — CloseAny of the seven prices, and several at once, each its own line with its own look.
  4. 4
    Timeframe — ChartThe chart's own by default; any higher one, read on the last closed candle. A finer one is never offered.
  5. 5
    Calculation — TA-LibOr MT5, which computes it as MetaTrader 5 does — see the calculation convention below.
  6. 6
    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

  • Applied priceWhich price of each bar is smoothed — the close by default.
  • CalculationHow the first value is made: from the simple average of the first N prices (TA-Lib) or from the first price (MetaTrader 5). It matters only for the first few periods of the chart.
  • ShiftDraws the line that many candles to the right, or to the left with a negative number. Its values do not change — only the candle each one stands on — so a shifted average is compared with a later price than the one it was computed at.
  • In use8 to 21 for short-term guides, 50 for the intermediate trend, 200 for the long one. The newest bar's weight is 2/(N+1): 18 % at N = 10, 4 % at N = 50, 1 % at N = 200.

13Calculation convention

This is one of the studies whose result differs between the two conventions Bentrix offers. The difference is in how the first values are seeded and how the series is smoothed, so the two agree after the warm-up and differ at its start. Choose it on the settings card's Calculation row.

defaultTA-Lib

The convention of the TA-Lib library, which most charting software follows.

MT5

Computed as MetaTrader 5 computes it, so a value matches the terminal's own.

14Limits and common misreadings

Never entirely forgets. A spike long ago still has a tiny weight. In practice it fades after a few periods.

Seeding. Values in the first few periods depend on the convention; compare EMAs from two platforms only after the warm-up.

15Conditions an alert or a strategy can watch

price crosses above the line eventprice crosses below the line eventprice is above the line stateprice is below the line state

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.

16Practise it in the laboratory

Put an EMA 20 and an SMA 20 on the same chart and play a sharp reversal. Note how many bars sooner the EMA turned — and then find a choppy stretch and count how many more times it turned for nothing.

Open the laboratory

18In Bentrix

  • From the menu: a chart's Indicators button › Moving averages › EMA, or type EMA in its search.
  • Its settings: the settings card opens when it is added; its legend's name opens it again.

19From 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": "ema"}).

The study, as a chart files it

This is a new EMA’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": "ema",
  "settings": {
    "period": 50,
    "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": "talib",
      "kind": "ema",
      "settings": {
        "period": 50,
        "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": "talib", "kind": "ema", "settings": {"period": 50, "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": "talib", "kind": "ema", "settings": { "period": 50, "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"] = "talib", ["kind"] = "ema", ["settings"] = new Dictionary<string, object?> { ["period"] = 50, ["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": "talib", "kind": "ema", "settings": map[string]any{"period": 50, "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", "talib", "kind", "ema", "settings", obj("period", 50, "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", "talib"}, {"kind", "ema"}, {"settings", Json::Object{{"period", 50}, {"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" => "talib", "kind" => "ema", "settings" => Dict{String,Any}("period" => 50, "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 = "talib", kind = "ema", settings = list(period = 50, 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": "talib", "kind": "ema", "settings": {"period": 50, "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
Mainline

In a strategy

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

WriteWhat it is
emaits main line, as a value in a compare
{"cond": "ema:price.cross_up"}a condition it declares itself
{"cond": "ema:price.cross_down"}a condition it declares itself
{"cond": "ema:price.above"}a condition it declares itself
{"cond": "ema:price.below"}a condition it declares itself

20Sources

  1. Murphy, John J. Technical Analysis of the Financial Markets. New York Institute of Finance, 1999, ch. 9.
  2. Brown, Robert G. Smoothing, Forecasting and Prediction of Discrete Time Series. Prentice-Hall, 1963.

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