Bentrix Docs
HomePricingDashboard

Simple Moving Average SMA

Moving averagesoverlayone linein every package

The arithmetic mean of the last N values of the applied price, every bar in the window weighted the same.

It measures where the centre of recent price sits; its slope is the direction of that centre. The readings are the line's level against price, the line's own slope, and the crossing of two lengths. MT5 and TA-Lib compute it identically.

01The study, live

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

02Its parts, named

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

03What you see

One line over the candles: at each bar, the plain average of the last N prices (closes by default). It is smooth where price is noisy, and it trails behind price — rising after price has risen, turning after price has turned.

04Where it comes from

The moving average is older than technical analysis: statisticians used running means to smooth series long before markets did, and it has no single inventor. In trading it became the most common tool of trend-following after the Second World War, and almost every other study on these pages either builds on it or was designed to fix one of its weaknesses — most often its lag.

05The formula

SMAt=1N∑i=0N−1Pt−i
Pt−ithe applied price i bars back — the close by default
Nthe period, in bars

where P is the applied price (the close by default) and N the period. Each new bar adds one price and drops the oldest; every price inside the window counts the same.

A five-bar example with closes 10, 11, 12, 11, 13: the SMA(5) is (10 + 11 + 12 + 11 + 13) / 5 = 11.4. On the next bar, if the close is 14, the 10 drops out: (11 + 12 + 11 + 13 + 14) / 5 = 12.2.

06A worked example

Take eight closes — 20, 21, 23, 22, 24, 25, 24, 26 — and a period of 3.

The first value needs three closes, so it appears on the third bar: (20 + 21 + 23) / 3 = 21.33. On the next bar the oldest close (20) leaves the window and the newest (22) enters: (21 + 23 + 22) / 3 = 22.00. Carried on, the line reads 21.33, 22.00, 23.00, 23.67, 24.33, 25.00.

Two things are visible in these few numbers. The closes run from 20 to 26, the average only from 21.33 to 25.00: it is always behind a moving price. And the close of 22, a step back of one point, lowered nothing: the average still rose from 21.33 to 22.00, because the close that left (20) was lower than the one that entered (22). An average moves by what enters and by what leaves.

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("Simple Moving Average", overlay = true)
length = input.int(20, "Length")
// The last `length` closes added up, and divided by how many there are.
total = math.sum(close, length)
sma = total / length
plot(sma, "SMA")

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. When price closes above a rising SMA, traders read it as the recent prices standing above their own average — the usual description of an up-trend. Below a falling SMA, the opposite.

The slope. A line that has turned from falling to rising is read as the average price of the window having started to climb.

Two averages. When a faster SMA (say 50) crosses above a slower one (say 200), traders read it as recent prices having moved above older ones; the popular names for the two directions are golden cross and death cross.

Distance. How far price stands from its average is read as how stretched the recent move is.

Support and resistance. Many traders watch where price meets a widely followed average — 50, 100 or 200 bars on a daily chart.

What a crossing of price and the line is, and when it fails. A close on the other side of the average says only that the newest close is above (or below) the mean of the last N closes. 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 drop-off effect. The line can turn because an old, extreme close leaves the window, with nothing happening on the newest bar. Traders who read the slope check which of the two moved it.

09In different markets and timeframes

A simple average is at its best in a market that trends for many times its period: price stays on one side and the line's slope says which. In a range narrower than the average's own lag it is at its worst — price crosses it every few bars. The same period means different things on different timeframes: 200 daily bars is most of a year, 200 one-minute bars a little over three hours. On charts built by price (Renko, range bars) each element is a fixed move, so the average is of equal-sized steps and is much smoother than on time candles.

10With other studies

Read beside a second average of another period (the 50 and the 200 are the classic pair), where the crossing replaces the price crossing; beside the ADX or the Choppiness Index, which say whether there is a trend for an average to follow; and beside a volatility band (Bollinger Bands are a simple average with a band around it), which says how far from the line is unusual.

11What it does not tell you

!

An SMA describes where prices have been, on average, over the window — nothing else. A cross or a turn happens after the move that caused it, by construction. On a sideways market, price crosses its average back and forth many times; most of those crossings are followed by another crossing.

12Inputs and defaults

SMA (20, 0)settings card
1Period20
2Shift0
3Applied priceClose
4TimeframeChart
5Wait for the candle to closeOn
  1. 1
    Period — 20The 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
    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 averaged — the close by default. An average of highs or of lows draws the same shape shifted up or down; the typical or median price damps a bar whose close sits at one end of its range.
  • 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 usePeriods in common use: 10 and 20 for short swings, 50 for the intermediate trend, 100 and 200 for the long one. Below about 5 the line is hardly smoother than price; above 200 it responds to almost nothing that happens in a month.

13Limits and common misreadings

Lag. The SMA's centre of gravity is half a window back: a 20-bar SMA describes, roughly, prices ten bars ago. A longer period is smoother and later.

The drop-out effect. When an unusually large price leaves the window, the SMA jumps — even though nothing happened on the current bar.

Period choice. No period is correct. 20, 50 and 200 are popular because they are popular; a test that tries many periods and keeps the best has learned the past, not found a rule.

The line does not start at the first bar. It needs N closes, so the first N − 1 bars have no value; on a short history a long average simply is not there.

Equal weights are a choice, not a law. A close twenty bars old counts exactly as much as the newest one, then drops to nothing a bar later.

14Conditions 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.

15Practise it in the laboratory

Open a replay of any market on H1, add SMA 20 and SMA 50, and play two weeks at ×720. Each time the two cross, pause and note what price did over the following twenty bars. Count how many crossings were followed by a lasting move and how many by another crossing. The point is to see the proportion with your own eyes.

Open the laboratory

17In Bentrix

  • From the menu: a chart's Indicators button › Moving averages › SMA, or type SMA 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": "sma"}).

The study, as a chart files it

This is a new SMA’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": "mt5",
  "kind": "sma",
  "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": "mt5",
      "kind": "sma",
      "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": "mt5", "kind": "sma", "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": "mt5", "kind": "sma", "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"] = "mt5", ["kind"] = "sma", ["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": "mt5", "kind": "sma", "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", "mt5", "kind", "sma", "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", "mt5"}, {"kind", "sma"}, {"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" => "mt5", "kind" => "sma", "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 = "mt5", kind = "sma", 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": "mt5", "kind": "sma", "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
Mainline

In a strategy

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

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

19Sources

  1. Murphy, John J. Technical Analysis of the Financial Markets. New York Institute of Finance, 1999, ch. 9 (Moving Averages).
  2. Colby, Robert W. The Encyclopedia of Technical Market Indicators, 2nd ed. McGraw-Hill, 2003, "Moving Averages".

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