Indicator · Pine Script v6 · Own pane

Ehlers MESA Stochastic (MSTOCH)

by mihakralj

Calculates John F.

View on GitHub

GitHub stars99on the repository
Pine versionv6current
Lines of code86
Settings4inputs
LicenceApache-2.0
Last update4 weeks ago27 Sep 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

86 lines of Pine Script v6 from lib/oscillators/mstoch/mstoch.pine, published under Apache-2.0. Keep the author's credit and licence lines when you reuse it.

mstoch.pine
// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
// Indicator algorithm (C) 2013 John F. Ehlers
// "Cycle Analytics for Traders", Wiley, 2013
indicator("Ehlers MESA Stochastic (MSTOCH)", "MSTOCH", overlay=false)

//@function Calculates Ehlers MESA Stochastic
//@param src Series to calculate MESA Stochastic from
//@param stochLength Lookback period for the stochastic highest/lowest calculation
//@param hpLength Cutoff period for the Roofing Filter highpass stage (default 48)
//@param ssLength Cutoff period for the Roofing Filter super smoother stage (default 10)
//@returns MESA Stochastic value (0 to 1 range, smoothed)
//@description Applies Ehlers Roofing Filter (HP + Super Smoother) to remove spectral
//  dilation, then computes stochastic on the filtered data, then smoothes the
//  stochastic with another Super Smoother for a clean oscillator output.
//  Reference: John F. Ehlers, "Cycle Analytics for Traders" (2013), Chapter 6
mstoch(series float src, simple int stochLength, simple int hpLength, simple int ssLength) =>
    float SQRT2_PI = math.sqrt(2.0) * math.pi

    // === Stage 1: Roofing Filter (HP + Super Smoother) ===

    // --- Highpass Filter (2-pole Butterworth, removes trend below hpLength) ---
    int safe_hp = math.max(hpLength, 1)
    float hp_arg = SQRT2_PI / float(safe_hp)
    float hp_exp_arg = math.exp(-hp_arg)
    float hp_c2 = 2.0 * hp_exp_arg * math.cos(hp_arg)
    float hp_c3 = -hp_exp_arg * hp_exp_arg
    float hp_c1 = (1.0 + hp_c2 - hp_c3) / 4.0

    var float hp = 0.0
    float ssrc = nz(src, src[1])
    float src1 = nz(src[1], ssrc)
    float src2 = nz(src[2], src1)
    float hp1 = nz(hp[1], 0.0)
    float hp2 = nz(hp[2], 0.0)
    hp := hp_c1 * (ssrc - 2.0 * src1 + src2) + hp_c2 * hp1 + hp_c3 * hp2

    // --- Super Smoother (removes noise above ssLength) ---
    int safe_ss = math.max(ssLength, 1)
    float ss_arg = SQRT2_PI / float(safe_ss)
    float ss_exp_arg = math.exp(-ss_arg)
    float ss_c2 = 2.0 * ss_exp_arg * math.cos(ss_arg)
    float ss_c3 = -ss_exp_arg * ss_exp_arg
    float ss_c1 = 1.0 - ss_c2 - ss_c3

    var float filt = 0.0
    filt := ss_c1 * (hp + nz(hp[1], hp)) / 2.0 + ss_c2 * nz(filt[1], hp) + ss_c3 * nz(filt[2], nz(hp[1], hp))

    // === Stage 2: Stochastic on roofing-filtered data ===
    float highestC = filt
    float lowestC = filt
    for count = 1 to stochLength - 1
        float val = nz(filt[count], filt)
        if val > highestC
            highestC := val
        if val < lowestC
            lowestC := val

    float range_val = highestC - lowestC
    float stoc = range_val > 0.0 ? (filt - lowestC) / range_val : 0.5

    // === Stage 3: Smooth stochastic with Super Smoother ===
    var float mstoc = 0.0
    mstoc := ss_c1 * (stoc + nz(stoc[1], stoc)) / 2.0 + ss_c2 * nz(mstoc[1], stoc) + ss_c3 * nz(mstoc[2], nz(stoc[1], stoc))

    // Clamp to valid range
    float result = math.max(0.0, math.min(1.0, mstoc))
    result

// ---------- Main loop ----------

// Inputs
i_stochLength = input.int(20, "Stochastic Length", minval=2)
i_hpLength    = input.int(48, "HP Length", minval=1, tooltip="Highpass cutoff period — removes cycles longer than this")
i_ssLength    = input.int(10, "SS Length", minval=1, tooltip="Super Smoother cutoff period — removes cycles shorter than this")
i_source      = input.source(close, "Source")

// Calculation
result = mstoch(i_source, i_stochLength, i_hpLength, i_ssLength)

// Plot
plot(result, "MSTOCH", color=color.yellow, linewidth=2)
hline(0.8, "Overbought", color=color.gray, linestyle=hline.style_dotted)
hline(0.2, "Oversold", color=color.gray, linestyle=hline.style_dotted)
hline(0.5, "Midline", color=color.gray, linestyle=hline.style_dotted)

Overview

Ehlers' MESA Stochastic oscillator by processing price data through a roofing filter before applying stochastic logic. The roofing filter combines a high-pass filter to remove low-frequency trend components and a super smoother filter to filter high-frequency noise. A stochastic calculation is then performed on the filtered series and smoothed once more using a super smoother stage. Settings allow configuration of the stochastic lookback length, high-pass cutoff, super smoother cutoff, and source series. Plots the resulting oscillator in a separate pane bounded between zero and one.

Details

Published by

mihakralj on GitHub

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

algorithmic-tradingcsharpdotnetpinescriptpythonquantitative-financesimdta-libtechnical-analysistechnical-indicators

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Stochastic Lengthint20i_stochLength
HP Lengthint48i_hpLength
SS Lengthint10i_ssLength
Sourcesourceclosei_source
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

Asymmetrical RSI

by everget
948 stars

Asymmetrical RSI is an indicator that computes a custom relative strength index from the rate of change of a user-selected source. It plots the resulting ARSI line in a separate pane with color coding that turns green above the overbought level and red below t

Indicator v4 Oscillators & momentum
Updated 10 days ago · GPL-3.0 GitHub repository of Asymmetrical RSI

This indicator calculates momentum setups based on the Relative Strength Index (RSI) and plots in a separate pane. It offers multiple scanning modes such as Continuous Break, Continuous Retracement, Flip Break, Flip Retracement, and both regular and hidden div

Indicator v6 Oscillators & momentumDivergence Repaints
Updated 1 year ago · MPL-2.0 GitHub repository of Momentum Setup - RSI Directional Momentum Indicator

Beep Boop

by magic8bot
409 stars

This indicator calculates a modified MACD oscillator and signal line alongside a trend EMA filter, plotting the output as a stylized column histogram in a separate pane. Instead of plotting true MACD distance, it quantifies positive and negative histogram mome

Indicator v4 Oscillators & momentumTrend
Updated 3 years ago · MIT GitHub repository of Beep Boop
261 stars

This indicator demonstrates an experimental graph-style scatter visualization within a separate pane using Pine Script arrays. It tracks two features across recent bars: the single-bar price change and a scaled 14-period Relative Strength Index. Values are loa

Indicator v4 Oscillators & momentum
Updated 4 years ago · None stated GitHub repository of Example: Graph Style - 4th Dimension RSI

KD指標

by TaichiS
219 stars

This script calculates and plots a Stochastic Oscillator (KD indicator) in a separate chart pane. It determines the fast stochastic value over a 9-period lookback, then applies a 3-period Simple Moving Average (SMA) to create the %K line, and a second 3-period

Indicator v4 Oscillators & momentum
Updated 5 years ago · None stated GitHub repository of KD指標

More indicators

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers