/, PowerLanguage Tutorial/EasyLanguage & PowerLanguage Tutorials – Lesson 02: Coding A Moving Average

EasyLanguage & PowerLanguage Tutorials – Lesson 02: Coding A Moving Average

EasyLanguage & PowerLanguage Tutorial – Lesson 02: Coding A Moving Average

Creating the first real indicator and expanding the basics

After you familiarized yourself with the PowerLanguage Editor in the previous PowerLanguage tutorial – lesson 01 we will now build up on this foundation. In case you haven’t read the last lesson, I would suggest doing that first as it can help you with understanding this lesson, too. Let’s start with today’s lesson now.

Open the PowerLanguage Editor and create a new Indicator study. I will name mine ABC_PowerLanguage Lesson 02 – Moving Average so I can find it easily within my editor later. The name is totally up to you of course and you could even change it later. As the last part of the indicator name suggests, we will create and plot a moving average today. You have probably seen a moving average on a chart before or remember the term average from math. The main use for averages is as a filter to smooth the data you input.

Simple moving average on price

The image displays a 200 period simple moving average that gives a very smooth outcome. The downside to this smoothness is that you introduce more lag. This means the average becomes less responsive to changes in price. If you take a look at the next image you will see how different the behavior of a 200 period simple moving average is when you compare it to the green 10 period average. The latter is much quicker in responding to price changes, but in turn there is a lot more “noise” in the average.

Two simple moving averages

There are many different types of averages that mainly vary in the impact each data point has on the outcome of the average. A 200 period simple moving average will simply compute a summation of the last 200 data points and divide it by 200. The result is an average which gives each data point the same influence (the same value) on the outcome. The first bar and the last bar that are part of the average are both weighted the same for the outcome.
Two other prominent and commonly used averages are the Exponential Moving Average and the Weighted Moving Average. Both have higher weighting factors for the more recent data points. In a weighted moving average the weighting will decrease in arithmetical progression. For the exponential average it will decrease exponentially, hence the name. This will be as theoretically as it will get for today. If you want to read some more details about averages, you can start with this Wikipedia article. For further understanding of this lesson you won’t need this additional information though.

Let’s start with coding our average. Our indicator should not only calculate an average, but it should output the result to a chart. EasyLanguage has the “Plot” reserved word for that and we will use it to do that. Before you start with programming something it’s always a good idea to take a step back and think about what you are trying to accomplish and how you are going to do it.
As this study is not very complex, there are only a few things to think through. When studies get more complex you can save a lot of time with good planning upfront.

    The goal is a study that calculates and plots a simple moving average.
    We want to be able to change the length for the average with an input so it’s easy to customize.
    For the average we need to sum the amount of values correlating to the length input. We don’t want to write code for every possible length input for the summation. This means the code needs to be able to calculate all possible length inputs on its own. Do you already have an idea how we could accomplish this?

The answer is that we need an iteration statement that can be executed repeatedly each bar for a specific number of times (our length input). I know this sounds complicated, but it will be quite simple. We will use the “for loop” for this task. This loop repeats one or more statements for a user defined, specific number of iterations. EasyLanguage code is executed from top to bottom and usually from left to right. Once one code line is executed, the next line is executed and so on. In case the code line is the beginning of a loop, the code lines within the loop will be executed for the specified amount. Only when the loop is finished the next code line after the loop is executed.
A for loop looks and works the following way:
A numerical variable will be incremented (or decremented) with every cycle through the loop from its start value to its end value.
This image displays a basic for loop with a numeric counter variable (ii in this case) and the initial value of 0. The iterations will be done ten times until the counter has reached the value of 9. Then the loop block is executed the last time and exited. You don’t have to increment the counter value yourself, the loop code takes care of that. The current counter value will be stored in the counter variable. So you can access it for every loop cycle and use it for your calculations. This will come in handy for calculating our average.

PowerLanguage For To Loop image

The for loop can also decrement the counter with every iteration. The initial value in this example is 9, but the loop is executed ten times until it is exited, too. The counter simply decreases with every iteration by one until it reaches 0.

PowerLanguage For Downto Loop image

In Easylanguage you can reference data-related reserved words, variables and functions from a previous bar very easy. Using a number within square brackets following the reserved word, calculation or variable will return the value for this particular bar. The number grows from the current bar (which you reference with [0]) in increments of one. When you want to store the value of the previous bar’s close within a variable called PrevCloseValue you can do it like this:

EasyLanguage previous bar values image

We want to build our average using the Close for the last X bars. Where X is an input to allow for more flexibility. You already know that we want to use a loop for that and we just found out how we can reference Close values for the previous bars. This should be enough to write the code for the main part of our indicator. Let’s continue by creating the input and variable sections. You might recall from the last lesson that using meaningful variable names is a good coding practice and can save you a lot of troubles later.

We need to declare one input so we are able to change the length for our average on the chart. Besides that we want one variable that holds the summation, one to hold the counter value and a last one to store the average value. For outputting the value on the chart we will use the reserved word Plot. This is followed by a number so you are able to distinguish between different plots. Which is needed as you can use up to 999 plots in Multicharts. The plot reserved word can have several parameters like color, plot size and some more. We will keep it simple here and use Plot1 with just two parameters – the first for the numerical expression to be plotted and a second one for the name we want to assign to the plot. The final code will look something like this:

simple moving average code image

After compiling this code we are almost ready to load our indicator to a chart in Multicharts. Let’s just take a look at the properties of the indicator first. You can find them under -> File -> Properties or by clicking on the Properties symbol in the menu (it should be the one left to Compile). Under the Style tab you can change the color, line style and thickness for the plot you created. If you go to the properties tab there are several options to set or check, but for now you might only want to make sure the option “Same As Symbol” is checked. This will make sure the indicator is applied directly on your chart rather than a subchart.

multicharts indicator properties image

Now you are ready to apply the indicator to a chart of your choice. When you have a chart open in the Multicharts main window you can simply insert the indicator to this chart.

strange moving average outcome image

When the indicator is applied the outcome should be similar to the above screenshot. However this doesn’t seem right as this doesn’t look like a moving average at all. The price series is almost a flat line and the plot coming from our indicator is only rising. With the E-Mini S&P 500 being in the area of 1’800 a 10 bar moving average value for this market of 1’952’647 is obviously not correct. This points towards a problem in our calculations. Do you have an idea what the code is missing? It actually is just a little, but very important detail we forgot to add. We need to add something in front of the for loop. The loop simply keeps on adding the values for the previous ten bars with every new bar. This is fine and we want it to do exactly this, but we don’t want it to add the new values to the old values. In other words you need to make sure CloseValueSum doesn’t still hold the old values when the for loop starts. With adding one line to the code the outcome is exactly what we wanted to achieve.

Multicharts moving average image

We can also change the indicator’s appearance on the chart. Using the style tab under “Format Study” we can alter the visual outcome like line style, color and thickness. Under the “Inputs” tab you will find the input you created and the default setting for the length. By loading a second instance of the study and using a different color and length you can confirm that the study gives a different outcome with a different length input.

two moving averages image

If you are having trouble finding the correct fix feel free to contact us with your solution and we will try to help you in a timely manner. I am afraid just asking for the solution won’t work though, you need at least be able to show that you put some effort into finding the solution, too. As a last hint you can take a look at other average indicators or functions and find some inspiration for the missing link there. I hope you enjoyed this Powerlanguage tutorial lesson and I am looking forward to working with you in the next one.

By |2017-09-04T14:42:18+00:00November 27th, 2013|Categories: EasyLanguage Tutorial, PowerLanguage Tutorial|Tags: , , |25 Comments

About the Author:


  1. stef November 28, 2013 at 6:48 pm - Reply

    Hello i wrote and compiled it as per the lesson and it worked correctly

    thanks stef

    • ABC November 29, 2013 at 8:12 am - Reply

      Good job and thanks for letting me know.

  2. Ross February 7, 2014 at 1:28 am - Reply


    Thanks for these tutorials. I coded it up and it worked fine, I wasn’t getting the error you said I would.
    I was actually hoping to break it to then find out how to fix it, but somehow it’s working fine..
    Any ideas?


    • ABC May 1, 2014 at 7:19 am - Reply


      I think I know why this happens (I already included the fix in the lesson) and I will change that.
      Thanks for letting me know.


  3. LT April 30, 2014 at 8:48 pm - Reply

    Hi, I’m having a problem on the line “PrevCloseValue = Close[1];” Can you tell me what I’m doing wrong?


    • ABC May 1, 2014 at 7:16 am - Reply

      I am only able to help you when you elaborate more on the problems you are having and include the error message for example. My guess is that you didn’t create a variable named PrevCloseValue.
      The line “PrevCloseValue = Close[1];” is just an example anyway and not needed for the moving average code.


  4. David December 5, 2014 at 5:46 am - Reply

    Hi there,

    With the extra line I think I see where you were going with this and by adding an extra line containing the AverageFC I thought that I had it. Then I decided to do a comparison with the Mov Avg 1 line and I could see that the lines with the same period were very close, specially when the stock was in a sideways range, but as the price movement went into a trend the ABC moving average preceded and moved away from the one out of the box. I checked the parameters and they appeared to be identical.

    Could you give me an idea of where I might be going wrong.


    • ABC December 6, 2014 at 2:26 pm - Reply


      there is no need to use the AverageFC in the code, this is what throws off your calculations.

  5. Thomas October 15, 2015 at 7:24 am - Reply

    I am learning the first time, so I’m sorry if my queston is too simply.

    So how to get the average to the chart ? I made File/Properties/Properties –> “Same as Symbol” but nothing happens. What else have to do ?

    • ABC October 15, 2015 at 7:44 am - Reply

      Hi Thomas,
      it’s hard to tell what is wrong without knowing the code you are using. If you are using the same code as in the tutorial, it should plot. If it’s not plotting
      or whatever “nothing happens” means, I can only assume that there is something missing. My suggestion would be to compare the codes line by line to check if there
      are any differences. If it’s exactly the same and still doesn’t plot you can post it here and I’ll take a look at it.


      • Thomas October 15, 2015 at 8:34 am - Reply

        Thank you for the answer.
        Here is the code – it should be the same.

        Price (Close),
        AverageLength (10);

        Counter (0),
        CloseValueSum (0),
        AverageValue (0);

        for Counter = 0 to AverageLength – 1
        CloseValueSum = CloseValueSum + Price[Counter];

        if AverageLength 0 then
        AverageValue = CloseValueSum / AverageLength;
        Plot1 (AverageValue, “Average”);

        • ABC October 15, 2015 at 8:56 am - Reply

          the code you posted doesn’t compile, as it’s missing a check in the third line from the bottom. If it did compile on your end, maybe this just got lost in the comment.
          When I add the missing piece here, your code compiles fine and I get a result similar to the third image from the bottom in Lesson 02.


  6. Thomas October 15, 2015 at 9:18 am - Reply

    Actually I noticed that missing “” that was because of copy paste, but originally it was/is there.

    Do I miss something ? For instance SPX 1 minute chart is open in MC64 for IB…

    • ABC October 15, 2015 at 9:23 am - Reply


      to be able to help, please answer the two questions below:
      1. Does the code compile on your end?
      2. What does the code display on the chart?

      Thank you,

  7. Thomas October 15, 2015 at 9:33 am - Reply

    1. Yes
    2. Nothing (looks like there is no connection between MC and editor)


    • ABC October 15, 2015 at 9:35 am - Reply

      Please create a new indicator in the editor and only use the following code in it:

      Plot1( Close );

      What does this plot on the chart?

  8. Thomas October 15, 2015 at 9:42 am - Reply

    I made and compiled it but nothing happens in the charts.

    Build started: ——
    Study: “ABC plot1” (Indicator)
    Please wait ….
    15.10.15 12:38:42
    —— Compiled successfully

    • ABC October 15, 2015 at 9:45 am - Reply

      Okay, that shows that the issue is somewhere related to your installation of MC. My guess would be that you are either running Multicharts
      as administrator, but the PL Editor not (or the other way around). If this is the case, simply run both as administrator and it should be fixed.
      If this is not the case, you should contact the MC support so they can troubleshoot it.


  9. Thomas October 15, 2015 at 9:58 am - Reply

    Thanks for your effort. By the way these lessons are great.

    • ABC October 15, 2015 at 10:53 am - Reply

      You are welcome. Thank you for your feedback.

  10. […] take a look at how you create functions by turning the moving average logic from lesson 2 into one. This should make things a little […]

  11. DM May 22, 2017 at 2:18 am - Reply

    Hi ABC,

    Great tutorial, truly enjoyed going through it.

    I came up with CloseValueSum = 0; inserting in front of the loop, and it seemed to solve the problem… except the plot is not the same as TS native Moving average line set to same length..
    Anything else I am missing?

    • ABC May 22, 2017 at 7:05 am - Reply

      Hi DM,

      I am glad to hear that you enjoy the tutorial. It’s hard to comment where the differences are coming from without knowing your full code and what study you used in TS exactly.



  12. Eduardo October 13, 2018 at 10:36 pm - Reply

    Code snippet removed to prevent spoilers for others. – ABC

    Would it fix it? I haven’t installed MC yet, I want to make full use of the trial period. So I’m only going to install it after I finish my studies.

    • ABC October 15, 2018 at 5:45 pm - Reply


      yes, in case you place your code line before the loop. You will just need to add a semicolon at the end of the expression.



Leave A Comment