Formulas

A line of chart script can calculate a formula and assign the result to a variable.

The result variable can be intended for use only within other formula lines in the ChartScript, or can be intended for display on the Security Chart. If the result variable is intended for display on the chart, it is designated by using the colon(:) syntax, whereas if it is intended as a calculation line only, it uses the colon equals (:=) syntax.

For example:

RAW:= V * (C - REF(C,1));
FI: EMA(RAW, N);

There are two formula lines in the above ChartScript. 

The first line uses the colon equals (:=) syntax, and so the line is a calculation only line where the result of the calculation is stored in the variable called RAW (the name on the left hand side of the ":=").

The second line is a line intended for display on the chart. It also performs a calculation and uses the value RAW that was calculated in the first line. If you applied this script to a chart area, you would see one line only, named FI. The RAW line is not generated for output to the chart, it is only used within the script.

In the above script you can also see shortcut names for some of the more common functions. V is short for Volume, C is short for Close. For a complete list of functions, see the function reference.

Everything to the right of the ":" or ":=" is a formula, where the result is assigned to the variable on the left hand side.

Functions in the formula can be expressed as if you were working with single valued variables, however behind the scenes each variable is a full array of data points and the calculation is applied to each of the data points.

For example:

Pivot: (H + L + C) / 3;

In the above formula line, H represents the High price of the stock for a bar, L represents the Low price and C the close price. The base 'pivot' point is found by calculating the average of High + Low + Close. The above line of script actually calculates this value for every bar on the chart, and assigns the result to the variable "Pivot" which is an array of data points that can be displayed in a chart area and the data points will line up with the main stock chart bars.

This is how the calculation would work on the following price history for stock XYZ:

 

 

12/1

12/2

12/3

12/4

12/5

12/7

12/8

12/9

12/10

High

10

11

12

11

10

9

10

11

12

Low

6

8

10

9

8

8

8

9

10

Close

7

11

11

10

9

9

9

10

12

The Pivot formula would result in an array where each element is calculated from the corresponding elements of the high, low and close arrays

 

Pivot

7.67

10

11

10

9

8.67

9

10

11.33

 

In ChartScript, you don't have to deal with the intricasies of arrays, you just write the formula as if you were calculating one bar only, and the script automatically performs the calculation for every bar. This avoids the need for writing loops and allows you to express the formula in a more natural way.