Professional Documents
Culture Documents
Esignal Core Java Script PDF
Esignal Core Java Script PDF
INTRODUCTORY TUTORIAL 2
Summary: The following items in this tutorial will cover the main aspects of Core JavaScript that
are most commonly used in EFS formula development. This tutorial does not cover all aspects
of Core JavaScript because there are many topics that are rarely or never used in EFS formula
development. The intent of this tutorial is to give the new user a solid start to understanding
JavaScript specifically for developing EFS formulas.
Topic List:
1. Description of JavaScript
2. Variables
3. JavaScript Syntax
4. Most commonly used Statements
5. Most commonly used Operators
6. Function Parameters
7. Core JavaScript Resources
1
2.1 Description of JavaScript
2.2 Variables
An important characteristic of JavaScript that often lead to coding errors for beginners is
that the language is a soft-typed, or untyped, programming language. What this means is
that you are not required to declare a variable with a specific data type. You are also
allowed to use, or recycle, the same variable to store different data types throughout your
code as needed. Also, the var keyword is not required to declare variables. It’s not a
recommended practice, but you can simply type a new variable name and assign a value
to it anywhere in your code.
As we mentioned in the previous section, using the var keyword to declare your variables
is optional. It’s highly recommended that you always use the var keyword to declare
variables. It becomes helpful when reading through your code during the
development/debugging process. More importantly, if you create all your variables as
globals, your formula will require more resources, which makes the formula less efficient.
Using local variables whenever possible is one way to help keep your formulas running
efficiently.
-2-
2.3 JavaScript Syntax
You might be wondering why the formula doesn’t generate an error on line 8. Remember,
the var keyword used to declare variables is optional in JavaScript. JavaScript is a
flexible language when it comes to variable declaration. Essentially, what happens on line
8 is that the EFS engine creates a new variable, nnumber, with an initial value of 12. Our
formula example really has two variables at this point. There isn’t any facility in the EFS
engine that will catch and alert you of this of type of error. It can’t make any decisions for
you and assume you meant to use nNumber. All the EFS engine sees is that you are
using two variables. It’s up to you to catch this type of mistake, which is referred to as a
logic error. This is where formula debugging will become an important part of your tool
set. We won’t go into this now, but there will be an entire tutorial dedicated to debugging
formulas later in the series.
3
The semicolon ( ; ) is used in JavaScript to tell the program it has reached the end of a
complete statement. This character is optional, however, we recommend that you get in
the habit of using it. It will help you avoid another common mistake in coding EFS
formulas. The issue is that JavaScript allows you to put more than one completed
statement on a single line of code. However, they must be separated by a semicolon,
otherwise you’ll get a syntax error. If you are already in the habit of using semicolons to
end your statements, you’ll be less likely to make this coding error. Consider the example
in Figure 2. On line 9, we have put two statements on the same line but left out the
semicolon after “nNumber = 12.” You can see the syntax error generated in the Formula
Output window (ToolsÆEFSÆFormula Output Window) when we try to apply this formula
to a chart. The EFS engine would know what to do if the two statements were on
separate lines. Without the semicolon, the engine tries to interpret line 9 as a single
statement, which by itself, is not proper syntax. After adding the semicolon after the “12”
on line 9, the formula will execute properly and print the result of nNumber (24) to the
formula output window. Try typing the code from this example into your EFS Editor
(ToolsÆEFSÆEditor) and make the correction to see the result for yourself.
4
your code and check it line by line to find the proper location for the missing brace. It’s a
good idea to save your work often and perform syntax checks as you go.
The multi-line comment symbols can also be used to comment a section of code that’s in
the middle of a line of code (see Figure 5). Using our previous code example for
nNumber, the result of
nNumber would now
equal 20. The
nNumber = 12;
statement is now
5
ignored. nNumber was initialized with a value of 10. Therefore, nNumber is now only
multiplied by 2.
2.3.5 Identifiers
Identifiers are nothing more than the names you use for your formula variables and any
user-defined elements. The general rule to follow when designing your naming
conventions for identifiers is to never start them with a number. Doing so will generate a
syntax error indicating that there is a missing variable name. Using special characters at
the beginning of an identifier will also generate errors, except for underscores (_) and
dollars signs ($). The following are examples of valid identifiers.
As you read through other user’s formula code you may notice that many programmers
use a naming convention where the first letter is lower case and the second is capitalized.
The first character typically indicates the intended data type for the variable where “n”
indicates a Number, “s” for String and “b” for Boolean. This is not a requirement but it
helps you and those reading your code understand what the code was intended to
perform.
6
Abstract enum isFinite super
arguments Error isNaN switch
Array escape long synchronized
boolean export Math SyntaxError
Boolean extends NaN this
break eval native throw
byte EvalError new throws
case false null transient
catch final Number true
char finally Object try
class float package typeof
const for parseFloat TypeError
continue function parseInt undefined
Date Function private unescape
debugger goto protected URIError
decodeURI if public var
decodeURIComponent implements rangeError void
default import ReferenceError volatile
delete in RegExp while
do Infinity rturn with
double instanceof short
else int static
encodeURI interface String
Numbers are self-explanatory. The important thing to know about numbers in JavaScript
is that they are all treated as floating-point values.
“”
‘’
“buy at market”
“123”
7
There are many core JavaScript functions used for manipulating strings. However, they
aren’t heavily used for EFS development so we’ll cover these methods later in the
Advanced tutorial series. For now, the important functionality of Strings that you should
be aware of is the ability to concatenate them to make larger strings. To concatenate, or
join, strings together we use the + symbol in the same way we would add two numbers
together. In figure 6, for example, the result of sString on line 15 creates the string, “Buy
100 IBM at Market!” when printed to the formula output window. Notice also that you can
incorporate numbers into string concatenations. The numbers may be a constant, such
as the 100 used in this example, or variables that store a number data type.
Boolean data types only have two values, true and false. These values are constants,
which are also represented as 1 or 0, 1 being true. Boolean variables in EFS
development are commonly used to keep track of events or conditions to control the
execution of specific code blocks within the formula. This type of Boolean variable is also
commonly referred to as a flag.
One example using a flag can be found in our EFS Library under Help Examples,
AlertOncePerBar.efs. In figure 7, the Boolean flag, vFlag, is used to prevent an alert from
signaling more than once per bar. The formula uses some made-up data for the sake of
demonstration, but you could easily modify the conditional statement on line 14 to detect a
particular event to suite your
needs. What happens with
this code is an audible alert
will sound on the first trade of
each bar in real time. If you
want to see the formula in
action, apply it to a chart with
a 1-minute interval. The
trade that triggers the alert
happens to be the first trade
of the bar because that is the
only instance where vFlag is
equal to (==) false and (&&)
vData1 is greater than (>)
vData2. The first time the
conditional statement on line
14 evaluates to true, vFlag
8
subsequently get set to true indicating that the alert has occurred for the current bar. So
for every trade after that during the 1-minute interval, the portion of the conditional
statement, vFlag == false, evaluates to false, which prevents the code block from lines 15-
17 from executing. Once the bar state of NEWBAR is detected again, vFlag is then reset
to false, which allows the condition on line 14 to evaluate to true again and so on.
Statements are a group of Core JavaScript keywords that are used to perform specific
behaviors or actions. Statements are the essential elements used that inevitably
determine the logic for a set of code. Each statement has a unique syntax that must be
followed. For beginning EFS development, the following statements, if(), else, function
and return are the most commonly used.
The else statement can also be immediately followed by another if() statement. This is
referred to as an else if() statement. This allows you to test collection of conditions in a
specific order and only execute the first one that is found to be true. Figure 10 illustrates a
simple example where a variable, sSymbol, is set to a specific value. In main, the tree of
9
if() and else if() statements check to see if that variable is equal to a particular symbol.
Since sSymbol is initialized with the value of “IDC,” the first two if() statements evaluate to
false. The third if() statement evaluates to true and prints “Symbol is Interactive Data
Corp.” to the formula output window.
10
This code example performs the exact same process as figure 10. Also make note of the
open and close parentheses ( () )after the name of the CheckSymbol function on line 14.
These characters used together is called the Function Call Operator, which is required
when defining the function and also when calling the function from within another function
such as main() (see line 9). The function call operator is explained in greater detail later in
this tutorial.
When the return statement is used to terminate the execution of a function, no value gets
returned. Any code in the function body that exists after a return statement that has been
executed will not be executed, thus terminating the rest of the function execution. Return
statements are often used in this manner when a function needs to validate a piece of
11
data before executing a routine. If a function does not have its required set of valid data
for the routine, there is no need to allow the function to continue to execute. This not only
helps improve the efficiency of your code, but also may prevent the calculation of
erroneous data due to the lack of valid components that a function may require. Figure 13
illustrates a basic example of this process. The code on line 8 is referred to as a null
check. This is a good programming practice
to use because it’s a good way to validate that
an expected return value exists before you try
to manipulate that data later in your code. In
this example, we did not return the nRet
variable from our calcNumber() function by
mistake. The result is that the if() statement
on line 8 will evaluate to true and execute the
return statement. Try adding some code
after the return statement, such as a
debugPrintln(“hello”) statement. You will see
that it does not execute. To correct the
formula, add the nRet variable back to the
return statement in the calcNumber() function.
There is one very important exception to the return statement behavior that is specific to
the EFS environment and not part of the core JavaScript. The return statement in main()
will always be the last line of code to be executed in an EFS formula. Therefore, the
eSignal application has been designed to receive this returned data, which allows the
Advanced Chart to display the results. There will be many examples of this return used
throughout the tutorial series as it is the primary purpose of EFS formula development. In
our example in Figure 13, the result of nNumber gets plotted in the Advanced Chart as a
non-price study (or indicator), which displays a horizontal line at 4.
In simple terms, operators are just special characters or words used for many purposes,
such as concatenating strings, performing math, or checking for equality or inequality to
name a few. This topic could be significantly large, so for the purposes of this tutorial we
will only cover the operators that you will use most often for EFS formula development.
For a complete list of operators, visit Chapter 5 Operators in the Core JavaScript 1.5
Reference of the EFS KnowledgeBase.
12
+ Addition
var nNum = 1 + 1 nNum is 2
var nNum = “1” + “1” nNum is “11”
var nNum = “1” + 1 nNum is “11”
var nNum = "1" + ("1" - 2) nNum is “1-1”
- Subtraction
var nNum = 1 - 1 nNum is 0
var nNum = “1” - 1 nNum is 0
var nNum = “1” - “1” nNum is 0
* Multiplication
var nNum = 2 * 2 nNum is 4
var nNum = “2” * 2 nNum is 4
var nNum = “2” * “2” nNum is 4
/ Division
var nNum = 4 / 2 nNum is 2
var nNum = “4” / 2 nNum is 2
var nNum = “4” / “2” nNum is 2
== Equality
if (5 == 5) Evaluates to true.
if (“5” == 5) Evaluates to true.
if (5 == 0) Evaluates to false.
if (“true” == true) Evaluates to false.
!= Inequality
if (5 != 5) Evaluates to false.
if (“5” != 5) Evaluates to false.
if (5 != 0) Evaluates to true.
if (“true” != true) Evaluates to true.
13
> Greater Than
if (5 > 5) Evaluates to false.
if (“5” > 5) Evaluates to false.
if (5 > 0) Evaluates to true.
<= Less or Equal
if (5 <= 5) Evaluates to true.
if (“5” <= 5) Evaluates to true.
if (5 <= 0) Evaluates to false.
>= Greater Than or Equal
if (5 >= 5) Evaluates to true.
if (“5” >= 5) Evaluates to true.
if (0 >= 5) Evaluates to false.
Make note also that the Comparison Operators can be used with Strings as well. The
difference is that the comparison is based on alphabetical order. However, this is rarely
used in EFS formula development.
+ Concatenation
“buy” + “ “ + “here” Evaluates to “buy here”
“sell ” + 100 + “ at Market” Evaluates to “sell 100 at Market”
When using these two logical operators, the expressions on either side converts to a
Boolean value. With the AND operator, both sides must evaluate to true in order for the
if() statement to evaluate to true. With the OR operator, only one side has to evaluate to
14
true. You can incorporate multiple logical operators into a single if() statement.
Depending on what you need to do, you may need to organize the expressions into
groups by enclosing them inside a set of parentheses like in the following example.
The Logical NOT operator simply inverts the value of a Boolean expression. For example,
if an expression evaluates to true and you then place the logical NOT operator in front of
that expression, it will evaluate to false.
! Logical NOT
if (5 > 4) Evaluates to true.
If !(5 > 4) Evaluates to false.
= Equals
var nNum = 5;
The variable “nNum” is assigned to the value of 5.
There are also some assignment operators that perform arithmetic and assignment at the
same time. They are simply short cuts for basic math operations. For example,
+=
nNum += 10;
This is a shortcut for nNum = nNum + 10;
-=
nNum -= 10;
This is a shortcut for nNum = nNum - 10;
*=
nNum *= 10;
This is a shortcut for nNum = nNum * 10;
/=
nNum /= 10;
This is a shortcut for nNum = nNum / 10;
15
2.6 Function Parameters
This is a very important topic to understand because EFS formula development is highly
dependant on the use of function parameters. When you start making requests for data, it
is the parameters passed to the EFS functions that tell the EFS engine what to return to
your formula.
An important note to make about the parameter variables of a user-defined function such
and nNum1 and nNum2 become local variables to the function. They do not need to be
declared anywhere in your formula code with the var keyword. Remember also that local
variables are only available to the function where they were created. You will not be able
to access those variable in any other function unless they are passed as parameters to a
function call within calcNumber().
16
2.6.2 Variables as Function Parameters
Variables may also be used as function parameters. In figure 14, we used constants, or
hard-coded values as parameters. Let’s consider an example where we create a new
variable and pass it as a parameter to the calcNumber() function. On line 7 we created a
new variable, nFirst, which is
assigned to our original
calcNumber() call with
constant parameters. On line
9, we’ve replaced the
constants with our nFirst
variable. nFirst gets
assigned to a value of 4,
which results in nNumber
receiving the value of 16.
This code example is also a
basic illustration of recycling
code through the use of a
function that we previously
discussed.
The core JavaScript topics discussed in this tutorial only highlight the most commonly
used aspects of the language for the new EFS developer. To learn more about the topics
discussed here and more elements of the JavaScript language please check out some of
the following resources.
• JavaScript for EFS Video Series – Nearly 6 hours of video tutorials that also covers
the core JavaScript concepts discussed in this tutorial plus many tips and tricks for
programming with JavaScript.
• Core JavaScript 1.5 Reference – This on-line book is the complete reference
manual for the core JavaScript language for version 1.5 located in our EFS
KnowledgeBase.
• Core JavaScript 1.5 Guide – This on-line book is a comprehensive guide that
covers all aspects of JavaScript 1.5 located in our EFS KnowledgeBase.
What’s Next?
17