Coding ema in pinescript

What is EMA ?
Ema is known as exponential moving average, it comes from the class of weighted moving average. It gives more weightage to the recent price changes, thus making it much more relevant to the current market analysis. Also it provides a dynamic way of calculating support and resistances in a trend following setup.
The most common way to mint profit out from the market is to use trend following setups which can be easily achieved by using a group of EMA’s

So how’s this EMA calculated ?

Before understanding the calculation of EMA let’s look into a much wider topic:
“The Law of Averages”
It states : If you do something often enough a ratio will appear, simply put, any time series data, tend to deviate from its average.
EMA provides a way to statistically calculate the exponential moving average for a provided time series data giving much more emphasis on the most recent data in the series.

So in the 17th century, when the people were playing with numbers in their free time, they came up with a statistical strategy to envelop any time series data to detect the direction of the data flow , they called it exponential moving average.

Later in 1940’s with the increase in signal processing requirements in the field of electronic devices scientists started using Exponential moving average onto the electronic signal followers, just to classify the signals as above or below a moving/dynamic threshold.

So EMA is a smoothed time-series data.
The simplest form of EMA Smoothing can be given by the formula:

S(t) = alpha * X(t) + (1 - alpha) * X(t - 1).

The value of alpha must lie between 0 and 1
alpha , is the smoothing factor
X(t) , is the current observation data point
X(t - 1), is the past observational data point.
t , is the current time

In current day trading setups for EMA the alpha is calculated by
alpha = 2 / (time period window + 1)

Things to note here is that the alpha calculated above is the most generally used factor calculation method for EMA ,
You can tweak the alpha function above until it gives value between 0 and 1 for example alpha can also be written as
alpha = ln ( current price / past price )
Note it’s just a weighing scheme,

But for Our Case of EMA
We will be using
alpha = 2 / (time period window + 1)

Please refer to the script code below

Open-source script

In true TradingView spirit, the author of this script has published it open-source, so traders can understand and verify it. Cheers to the author! You may use it for free, but reuse of this code in a publication is governed by House Rules. You can favorite it to use it on a chart.


The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.

Want to use this script on a chart?