Indicator · Pine Script v5 · Own pane

Linear Moments

by Teerth1· code credited to Motgench

Calculates L-moments of a rolling window of log returns or the raw source: the mean, L-scale, L-skewness and L-kurtosis.

View on GitHub

GitHub stars1on the repository
Pine versionv5runs as is
Lines of code126
Settings12inputs
LicenceNone statedfile: MPL-2.0
Last update6 months ago10 Apr 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

126 lines of Pine Script v5 from deal-api/src/main/resources/PineScript/Linear Moments.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

Linear Moments.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Motgench

//@version=5
indicator('Linear Moments', precision=10)

MN = 'Mean'
VA = 'Scale'
SK = 'Skewness'
EK = 'Kurtosis'

LR = 'Log Returns'
OS = 'Original Source'

NO = "Normal"
LA = "Laplace"
ST = "Student-T (df = 2)"


src = input.source(close,     "Source",                   group = "Source settings"                             )
sl  = input.string(LR,        "Source Selections",        group = "Source settings",    options = [LR,OS]       )
ms  = input.string(MN,        "Moments Selections",       group  = "Moments Settings",   options=[MN, VA, SK, EK])
len = input.int(300,          "Lookback" ,                group  = "Moments Settings"                            )
cs  = input.string(NO,        "Theoretical Distribution", group  = "Moments Settings",   options = [NO,LA,ST]    )

cm1 = input.color(color.rgb(244, 25, 9),       "mean < 0",                      group = "Color Selection")
cm2 = input.color(color.rgb(39, 255, 111, 1),  "mean < 0",                      group = "Color Selection")
cv =  input.color(color.orange,                "L-Scale",                            group = "Color Selection")
cs1 = input.color(color.rgb(233, 3, 53),       "L-Skewness < 0",                        group = "Color Selection")
cs2 = input.color(color.rgb(0,255, 119),       "L-Skewness > 0",                        group = "Color Selection")
ck1 = input.color(color.rgb(0, 255, 195),      "L-Kurtosis < theoretical_distribution", group = "Color Selection")
ck2 = input.color(color.rgb(163, 106, 255),    "L-Kurtosis > theoretical_distribution", group = "Color Selection")


rx = math.log(close / close[1])

f_S(_sl) =>
    _sl == LR ? rx : src

r = f_S(sl)

var arecord = array.new_float(len+1)
var asort = array.new_float(len)

if bar_index > 0 
    array.unshift(arecord,r)
    array.pop(arecord)

var x1=0.0
xn = bar_index > len ? array.get(arecord,len) : 0
x1 := nz(x1) + r - xn

if bar_index == len
    asort := array.copy(arecord)
    array.sort(asort)

if bar_index > len
    a0 = array.get(arecord,len)
    aid = array.binary_search(asort,a0)
    array.remove(asort,aid)
    searchid = array.binary_search_rightmost(asort,r)
    array.insert(asort,searchid,r)



B0 = x1/len
sB1 = 0.0
sB2 = 0.0
sB3 = 0.0
for i = 1 to len-1
    
    j = i + 1
    sx = array.get(asort, i)
    j1 = j-1
    j2 = j-2
    j3 = j-3
    j12 = j1*j2
    
    sB1 += sx * j1
    sB2 += sx * j12
    sB3 += sx * j12*j3


var len1 = len-1
var len2 = len-2
var len3 = len-3

var lenb1 = 1/(len*len1)
var lenb2 = 1 / (len*len1*len2)
var lenb3 = 1/(len*len1*len2*len3)

B1 = sB1*lenb1
B2 = sB2*lenb2
B3 = sB3*lenb3

L2 = 2 * B1 - B0
L3 = 6 * B2 - 6 * B1 + B0
L4 = 20 * B3 - 30 * B2 + 12 * B1 - B0

Mean = B0
t2 = L2
t3 = L3 / L2
t4 = L4 / L2

f_D(_cs)=>
    _cs == NO ? 0.1226 :  _cs == LA ?   0.2357   :   0.375

d_t4 = f_D(cs)

c_mean = Mean > 0 ? cm2 : cm1
c_scale = cv
c_skew = t3>0 ? cs2 :cs1
c_kurt = t4 < d_t4 ? ck1 :ck2

//Function Returns the selected Moments
f_M(_ms) =>
    _ms == MN ? Mean : _ms == VA ? t2 : _ms == SK ? t3 : _ms == EK ? t4 : float(na)

f_C(_ms) =>
    _ms == MN ? c_mean : _ms == VA ? c_scale : _ms == SK ? c_skew : _ms == EK ? c_kurt : color(na)

out_c = f_C(ms)
out = f_M(ms)
hline(0)
plot(ms == EK ? d_t4 : na,"Theoretical Kurtosis",color=color.white, show_last=1,trackprice = true)
plot(out, "Linear Moment", color = out_c)

Overview

A selector chooses which moment is plotted, and the lookback sets the window size. For kurtosis it draws a reference level for a chosen theoretical distribution: normal, Laplace or Student-t with two degrees of freedom. Line colours change with the sign or comparison. It plots in a separate pane without trading signals.

Details

Published by

Teerth1 on GitHub

Code credit

Motgench, as written in the script's header

Draws

Separate pane below the chart

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.

Settings

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

SettingTypeDefaultVariable
Sourcesourceclosesrc
Source SelectionsstringLRsl
Moments SelectionsstringMNms
Lookbackint300len
Theoretical DistributionstringNOcs
mean < 0colorcolor.rgb(244, 25, 9)cm1
mean < 0colorcolor.rgb(39, 255, 111, 1)cm2
L-Scalecolorcolor.orangecv
L-Skewness < 0colorcolor.rgb(233, 3, 53)cs1
L-Skewness > 0colorcolor.rgb(0,255, 119)cs2
L-Kurtosis < theoretical_distributioncolorcolor.rgb(0, 255, 195)ck1
L-Kurtosis > theoretical_distributioncolorcolor.rgb(163, 106, 255)ck2
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

This indicator calculates the distribution of close-to-close percentage changes using rate of change on closing prices. It bins percentage changes into intervals of 0.25 percent increments from negative to positive values and plots a normalized cumulative hist

Indicator v4 Volatility & bands
Updated 12 days ago · GPL-3.0 GitHub repository of Close-to-Close % Change Distribution

This indicator plots a Supertrend-based trend-following setup in a separate pane and skips conditions it treats as a sideways market. A volatility range is built from an ATR value, with RMA, SMA, EMA, or WMA smoothing, or from a fixed point distance. Optional

Indicator v5 TrendVolatility & bands
Updated 1 year ago · MPL-2.0 GitHub repository of Trend Following Setup - Sideways Market Skipper
330 stars

This indicator plots candle range and open-to-close movement as percentages in a separate pane. Range is the high-low difference divided by the low, and change is the close-open difference divided by the open. Both series draw as columns. Teal columns show ran

Indicator v5 Volatility & bands
Updated 2 months ago · None stated GitHub repository of Percent & Volatility [Alorse]

Mojito v3 Strategy

by namuan
318 stars

The Mojito v3 Strategy indicator evaluates volatility term structure by calculating the ratio between front-month and second-month VIX futures contracts. It smooths this ratio using a configurable median filter and compares the result against user-defined uppe

Indicator v5 Volatility & bands
Updated 2 months ago · MIT GitHub repository of Mojito v3 Strategy

Function - Logistic Equation

by ricardosantos79
261 stars

Calculates dynamic modeling values by applying a mathematical logistic differential equation to price change over a specified lookback length. It measures price momentum relative to the recent high-low price range. The script plots positive and negative logist

Indicator v5 Oscillators & momentumVolatility & bands
Updated 4 years ago · None stated GitHub repository of Function - Logistic Equation
228 stars

This indicator detects a Bollinger Band squeeze when the bands sit inside Keltner Channels, marking low volatility. It plots red dots during a squeeze and green dots when the bands are outside, in a separate pane. An optional histogram shows momentum as the cl

Indicator v6 Volatility & bandsOscillators & momentum
Updated 3 months ago · None stated GitHub repository of Bollinger Band Squeeze Detector

More Volatility & bands scripts

Related on ForexR

Trade Your Charts With a Regulated Broker

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

Compare brokers