Вы находитесь на странице: 1из 155

Getting Started with BullScript

Table Of Contents
Welcome to BullScript......................................................................................................... 1
Using This Manual.......................................................................................................... 1
Printing This Manual ...................................................................................................... 1
Learning BullScript ............................................................................................................. 3
Learning BullScript......................................................................................................... 3
Language Overview........................................................................................................ 3
Operators......................................................................................................................... 3
Price Variables ................................................................................................................ 4
Security Variables ........................................................................................................... 5
Using 'If'.......................................................................................................................... 8
Hist, Future and Previous Functions ............................................................................... 9
Variables ......................................................................................................................... 9
Defining Formulae with Parameters ............................................................................. 10
Referencing Other Formulae......................................................................................... 11
Multiple Plots................................................................................................................ 11
Comments ..................................................................................................................... 11
Attributes ...................................................................................................................... 12
Functions....................................................................................................................... 16
Candle Patterns ............................................................................................................. 17
Displaying Text............................................................................................................. 20
Function Reference............................................................................................................ 23
Function Reference ....................................................................................................... 23
General.......................................................................................................................... 23
Mathematical ................................................................................................................ 34
Candle Pattern............................................................................................................... 49
Pattern Recognition....................................................................................................... 64
Date and Time............................................................................................................... 66
Highest/Lowest ............................................................................................................. 70
Indicator Functions ....................................................................................................... 74
Attribute reference........................................................................................................... 111
Attribute Reference..................................................................................................... 111
Attributes .................................................................................................................... 111
Color Attribute ............................................................................................................ 116
FillStyle Attribute ....................................................................................................... 119
LineStyle Attribute...................................................................................................... 120
Target Attribute ........................................................................................................... 127
Best Practices................................................................................................................... 129
Sample Scripts ................................................................................................................. 131
Exponential Moving Average...................................................................................... 131
Gap Up........................................................................................................................ 131
Simple Moving Average ............................................................................................. 131

iii
Getting Started with BullScript

Typical Price ............................................................................................................... 131


Weighted Close ........................................................................................................... 131
Sample Indicator.............................................................................................................. 133
A Simple Stochastic Oscillator Script......................................................................... 133
The BullCharts Stochastic Oscillator Script ............................................................... 133
Description and Citation ............................................................................................. 134
Target Attribute ........................................................................................................... 135
Category Attribute....................................................................................................... 135
Alias Attribute............................................................................................................. 135
Horzlines..................................................................................................................... 136
Inputs .......................................................................................................................... 136
The %K Line............................................................................................................... 136
The %D Line............................................................................................................... 137
Markers ....................................................................................................................... 137
Troubleshooting............................................................................................................... 139
Error Codes...................................................................................................................... 141
Index................................................................................................................................ 145

iv
Welcome to BullScript
Manual updated: 26th May 2005

BullScript is a powerful, yet easy to use, scripting language that you can use to create your
own tools in BullCharts.
You can use BullScript in the following scenarios:

• Design your own indicators.


• Create signals to alert you of signficant patterns.
• Build more advanced market scans.

Using This Manual


This help program allows you to learn about BullScript in three ways:

1. Use the Contents tab to read through the help in a structured order, or to find
articles grouped by topic.
2. Use the Index tab to find a specific article by keyword. For example, to find
details on a specific function.
3. Use the Search tab to perform a full-text search on all articles in this help file.

Use the Learning BullScript help topics to learn about how BullScript works, and use the
function reference and attribute reference help topics to learn about the different tools
available to you in BullScript.

Printing This Manual


If you would prefer to print this manual, please download the PDF version from the
Downloads section of the BullCharts web site.

1
Learning BullScript
Learning BullScript
The following pages will teach you about the main language features of BullScript such as
how to use functions, and attributes.
For details on specific functions, please refer to the Function Reference, or to the index.

Language Overview
BullScript is a functional programming language that is used to define indicators and
alerts. It is similar to some spreadsheet languages. The language is made up of functions,
such as ma() and atr(), and mathematical operations like +, -, *.
BullScript is not case sensitive, meaning that it doesn’t matter if words are typed in upper
case or lower case.

Operators
BullScript provides fourteen basic operators for doing mathematical calculations. These
are divided into five arithmetic operators: +, -, *, /, and ^, the six relational operators: <, >,
<=, >=, <>, =, and two logical operators: 'and', and 'or'. There is also an operator called the
assignment operator, :=, which is used to store a value in a variable.
The operators, in order of precedence, are:

Operator Name Example

^ Exponentiation 3^4 ? 81

* Multiplication 4*5 ? 20

/ Division 20/5 ? 4

+ Addition 4 + 5?9

- Subtraction 4 - 5 ? -1

< Less Than 4 < 5 ? true

3
Getting Started with BullScript

> Greater Than 4 > 5 ? false

<= Less Than or Equal To 4 <= 5 ? true

>= Greater Than or Equal To 4 >= 5 ? false

= Equal To 4 = 2+2 ? true

<> (or !=) Not Equal To 4 <> 5 ? true

and Logical And Close>5 And Volume > 10000

or Logical Or Close>5 Or Close<3

:= Assignment result := (High + Low) / 2

Logical Operators
The AND and OR operators are called logical operators. They are uesd to combine
true/false calculations together.
The expression H>hist(H,1) AND L>hist(L,1) will return true if both the high
and the low have increased over the last day.
The OR operator is an inclusive or, which means it returns true if either, or both, of the
expressions on each side are true. For example, H>hist(H,1) OR L>hist(L,1)
will return true if the high has increased, or the low has increased, or both have increased.

Price Variables
BullScript allows use of special variables to access the open, high, low, and close prices,
and the volume of the current bar the formula is being run on. The valid BullScript price
variables, and possible abbreviations are shown in the table below.
For example, the formula (H+L)/2 will plot the average of the high and low prices. The
formula H+1 will plot a line $1.00 above the high price.

Price
Abbreviation Description
Variable

Open O The opening price, or first traded price.

High H The highest price achieved during the interval.

4
Learning BullScript

Low L The lowest price achieved during the interval.

Close C The closing price, or last price traded for the interval.

Volume V The total volume traded in the interval.

The total cost of all trades in the interval. Also called


Value none
turnover.

Trades none The number of trades made in the interval.

See Also
Security Variables

Security Variables
If you have subscribed to receive data from BullSystems, a number of security details, or
fundamentals, are also available such as PE ratio, earnings per share, and industry
information.
To reference a security variable, enter the word code Security. followed by the
variable to be included. For example Security.PERatio. See below for a table of all
security variables.

Important notes regarding security variables


The underlying data for the security variables is a static snapshot. That is, the historical
values of that variable are not recorded, and only the latest values are available to
BullScript.
Some of the security variables (for example earnings per share) report directly from the
fundamentals data stored in the database. Others perform a calculation, such as market
cap, which is close * total issue.
If you reference a non-calculated security variable then it will always have the same value
for every day being calculated (even if you select a historical date in a BullScan, offset the
data, etc). On a chart it will appear as a straight line.
If you reference a calculated security variable then any price variables used to internally
make the calculation will be for the current day, but the fundamentals will not change.
The above limitations mean that security variables are only representative of the
current day - and therefore must be used with caution. Their primary application is for
BullScans on the current day.

5
Getting Started with BullScript

Table of security variables


Each of these should be used as Security.Name. Some variables have multiple names,
or aliases. Any may alias may be used. Unl

Security Variable Description Units Calculation*

Total class issue. The


total number of
TotalIssue securities of this class Shares Non-calculated
quoted on the
exchange.

Net Tangible Assets as


AssetBacking
last reported by the
NetTangibleAssets $/share Non-calculated
NTA company, adjusted for
dilution.

EarningsPerShare Rolling 12 months


$/share Non-calculated
EPS earnings per share.

Rolling 12 months
DividendPerShare
dividend rate per $/share Non-calculated
DPS
share.

Value of most recent


CurrentDividendAmount dividend (net of $/share Non-calculated
witholding tax).

The percentage of the


FrankedPercent
dividend on which tax % Non-calculated
Franked
has already been paid.

Gross dividend
GrossDividendAmount $/share Non-calculated
amount.

Total dividend rate per


share over the last 12
AnnualDividendPerShare months, including any $/share Non-calculated
special cash or scrip
dividend.

MarketCap The current $ Close*TotalIssue

6
Learning BullScript

capitalisation of this
security.

Earnings per share as a


EarningsYield % 100*EPS/Close
percentage of price.

PERatio
Price Earnings Ratio Close/EPS
PE

Dividends per share as


DividendYield % 100*DPS/Close
a percentage of price.

Ratio between
DividendCover earnings and times EPS/DPS
dividends.

Shares purchased after


ExDate this date will not Date Non-calculated
receive dividends.

Dividend payments
DividendPayableDate Date Non-calculated
are made on this date.

8 digit GICS (Global


IndustryCode
Industry Classification Text Non-calculated
GICS
System) industry code.

Name of GICS sector.


Sector First of four levels of Text Non-calculated
classification.

Name of GICS
industry group.
IndustryGroup Text Non-calculated
Second of four levels
of classification.

Name of GICS
industry. Third of four
Industry levels of classification. Text Non-calculated
Not available for
many securities.

7
Getting Started with BullScript

Name of GICS sub-


industry. Fourth of
four levels of
SubIndustry Text Non-calculated
classification. Not
available for most
securities.

The S&P/ASX200
index symbol for the
sector that the security
SectorIndex belongs to. Useful Text Lookup
when used in
conjunction with
LoadSymbol.

* Refers to calculations made on underlying data by BullScript.

Example
if( Security.MarketCap > 100000000 and Security.Franked =
100, 1, 0);

See Also
Price Variables | LoadSymbol

Using 'If'
An important function in BullScript is the If function. If accepts three parameters. If the
first parameter is not zero, then it will evaluate to the second parameter, otherwise it will
evaluate to the third parameter.
For example, if you wanted to plot an indicator that is equal to the volume for the bar on
all bars where the closing price is greater than the opening price, and is equal to the
negative of the volume otherwise, you could use the formula If(close > open,
volume, -volume). If is very important, because it allows completely different
calculations to take place depending on whether a condition is true or not.

See Also
If function

8
Learning BullScript

Hist, Future and Previous Functions


Many indicators require use of data before the current bar. The Hist function is useful for
accessing data from previous bars. Hist accepts two parameters: the data value being
looked for, and the number of bars ago to look at.
For instance, hist(C,1) finds the close price for the previous bar. hist((H +
L)/2,8) finds the average of the high and low prices for 8 bars ago.
The Future function is like the Hist function, except that it evaluates bars that are in the
future from the current bar being evaluated. For instance, future(C,1) finds the close
price for the next bar.
The Previous function is like the Hist function, except that it evaluates to the value of
the current formula for a certain number of bars ago, usually the previous bar. Note that
the value of the current formula a certain number of bars ago will itself also rely on the
value of the formula further bars ago, and so in effect the entire data set can be accessed
using Previous.
For example, to add up all the close prices that have occurred, one could use the formula:
close + previous(0,1)
The first parameter to Previous is the 'seed'. That is, the value to use if there is no previous
bar available. The second parameter is the number of bars ago to look at. The most
common uses of Previous use 0 as the seed and 1 as the number of bars ago to look at, and
so those are the parameters that will be used if no parameters are given. Thus the above
formula can be written: close + previous
Previous, Hist and Future are important BullScript functions, and many indicators
would be impossible to plot without them.

See Also
Future | Hist | Previous

Variables
Some indicators require long and complex formulae. To make long BullScript formulae
simpler and easier to understand, partial results of a formula can be placed in a variable,
and that variable accessed later.
For instance, if one wanted to find the 14-day simple moving average of the typical price
(the typical price is the average of the high, low, and close prices), the formula,
MA((high + low + close)/3,14,SIMPLE) could be used.
This could be simplified by putting the typical price in a variable:

9
Getting Started with BullScript

TypicalPrice := (high + low + close)/3;


MA(TypicalPrice,14,SIMPLE)
For even large formulae, the usefulness of variables is even larger. One may also access
variables used in another formula. This is done by placing the name of the formula,
followed by a dot, ‘.’, followed by the name of the variable. For instance, if the above
formula was called Typical14MA, then the variable could be accessed using
Typical14MA.TypicalPrice.

Defining Formulae with Parameters


It is possible to create a BullScript formula that accepts parameters, like many builtin
functions do. If you use a formula that accepts parameters, you will be asked to enter the
values of the parameters. If you use a formula that accepts parameters like a function,
parameters may be given to it in the same way as parameters are normally given to a
function.
There are three BullScript functions that facilitate a formula accepting parameters: the
Input, Param, and Expression functions.
The Input function will make the formula accept a parameter, and will evaluate to the
value of the parameter. The parameter given must be a number, and must not rely on any
plot data. For instance, if you wanted to write a formula called AvgAD, which calculates a
moving average on the accumulation/distribution (calculated by the standard ad function),
your formula might be written as:
MALength := input("The length of the moving average");
ma(ad,MALength);
When you try to insert the AvgAD indicator, you will be asked for a parameter with the
prompt "The length of the moving average". If you use AvgAD as a function, you may
simply type AvgAD(14), for instance, to find a 14 day moving average of
accumulation/distribution. You may not however, type AvgAD(close) since using price
variables as the parameter to the Input function is not allowed.
The Param and Expression functions are like the Input function, except that they
allow price variables to be given. See the specific notes for each of these functions for
more details.

See Also
Expression | Input | Param

10
Learning BullScript

Referencing Other Formulae


If you write a formula in BullScript, that formula can be used as a function from another
formula. For instance if you wrote a formula (H+L)/2 which you named HLAvg, and
you wanted to run it as a function from another formula, you could simply write
HLAvg() and it would treat it as a function.
However, functions in BullScript may not contain spaces, or any characters other than
letters, numbers, or underscores. They may not begin with a number. If your formula is
not named in this way, then it may not be used directly as a function. You can still access
it though, using the formula function. The formula function is used to access any formula
as a function, and is given the name of the function as its first parameter.
If you named your formula High Low Average, you could write formula("High Low
Average") to use it as a function from another formula.

See Also
Formula function

Multiple Plots
A single BullScript formula can plot multiple lines in an indicator. This is done by
seperating the calculations for each plot by a semi-colon (;). If for instance, you wanted to
plot a line $1 above the high price, and another line $1 below the low price, you could use
the formula:
High + 1;
Low - 1
A single formula can have an unlimited number of plots.

Comments
BullScript allows you to write comments, or notes, to yourself within a formula by placing
the comments in braces: { and }. Comments can be used to make the formula easier to
understand when it is read later.
The following example shows how a comment may be used to more clearly indicate what
a formula is doing. The syntax highligher will show comments in green:
ma(C,20) {a 20 day moving average}
BullCharts will completely ignore all comments. Therefore comments can also be a
convenient way to temporarialy remove some code while testing your scripts.

11
Getting Started with BullScript

Attributes
Using Attributes
BullScript allow you to specify the way you want the results of a script to be displayed
within the script itself, using its attributes system.
Attributes are defined within square brackets, ‘[‘ and ‘]’, and appear before the plots that
they relate to. They consist of the name of the attribute being used, followed by an ‘=’,
followed by the value of the attribute.
For instance, if you wanted to plot a 28-day simple moving average and a 14- day simple
moving average, but you wanted the 28-day moving average to be displayed in green, and
the 14-day moving average to be displayed in red, you could use the following code:
[color=green]
ma(C,28,SIMPLE);
[color=red]
ma(C,14,SIMPLE);
If a plot has more than one attribute, the attributes may be seperated by semicolons, or
placed in separate sets of square brackets. For example, if you wanted to plot a 14-day
moving average in red, on a new pane, you could use,
[color=red; target=price]
ma(C,14,SIMPLE);
or
[color=red]
[target=price]
ma(C,14,SIMPLE);
Some attributes, such as author and category may take multiple values. All values must be
given in the same attribute, and must be separated by pipes. See the table below for
details.
[category=Moving Average|Verticality]
ma(C,14,SIMPLE);

Available Attributes
Possible
Attribute Description Examples
Values

An alternative
Alias Any text name by [alias=MyRSI]
which the

12
Learning BullScript

formula may
be called
within
BullScript.
This will often
be an
abbreviation.

The author of
the indicator.
By
convention,
use the last
Any text (for [category=Hull, Alan]
name then the
Author example Hull, [category=Guppy,
first name.
Alan) Daryl|Wilson, Leon]
Multiple
authors may
be listed,
separated by
pipes.

The category
that the
formula is in.
Any text (for Multiple [category=Moving Average]
Category
example Volume) categories may [category=Volume|My Own]
be listed,
separated by
pipes.

A reference to
documentation
[citation="Trading Systems,
Citation Any text on which the
Wilder"]
formula is
based.

Colour names or
The default
RGB values given [color=red]
Color colour of the
as [color=rgb(0,255,128)]
plot.
rgb(red,green,blue)

Description Any text A description [description="The moving


of the formula. average can be used to

13
Getting Started with BullScript

This will smooth noisy data"]


appear on the
Insert
Indicator page.

Background
Name of pattern to
FillStyle pattern for [fillstyle=Weave]
use. See list.
ribbons.

Default, or any The font face,


font name, eg: or family, used [font="Courier New"]
Font
Verdana, Arial, for markers [font=Default]
Wingdings and text plots.

The size of the


Default, or a font in points [fontsize=12]
FontSize
positive number. for markers [fontsize=Default]
and text plots.

Default, or any of
The style of
Bold, Underline,
the font for [fontstyle=Bold,Underline]
FontStyle Italic or Strikeout
markers and [fontstyle=Default]
separated by
text plots.
commas.

Levels at
List of numbers which
HorzLine separated by horizontal [horzline=20,80]
commas. lines should be
displayed.

Solid, Dotted,
Dash, Long Dash,
Step, Dotted Step, The style with
LineStyle Horz Step, Bar, which the plot [linestyle=step]
Grounded Bar, will be drawn.
Points, Marker,
Fill, NoPlot, Text.

If an indicator
LinkedChart SelectionOnly has this [linkedchart=selectiononly]
attribute and it
is included in a

14
Learning BullScript

scan, then
when a linked
chart is
created, only
selected plots
are shown on
the chart.

The name for


Name Any text an individual [name=Signal Line]
plot.

The password
must be
entered to
view or edit
Password Text [password=12345]
the indicator
script again -
but not to use
the indicator.

The timeframe
that this
indicator
Daily, Weekly, intended for
Period Monthly, use on. Do not [period=Weekly]
Quarterly, Yearly specify if the
indicator can
be used on any
timeframe.

Normally an
indicators
plots are
shown in the
properties
window in the
SortPlots ByName [sortplots=byname]
order they are
scripted. This
attribute
causes them to
be sorted by
name.

15
Getting Started with BullScript

Price, Volume, The pane and


New Pane, New scale that the
Target [target=price]
Axis, Overlay, plot will use
Percent, Default by default.

Specifies
[TextAlign=Above, Left]
Center, Above, where text is
TextAlign [TextAlign=Right, Center]
Below, Left, Right placed relative [TextAlign=Below]
to a data point.

Allows
advanced
formatting
[TextFormat=00 00 00 00]
Default, other options for
TextFormat [TextFormat=E]
format string displaying [TextFormat=default]
dates and
numbers as
text.

Specifies the
transparency
for a filled
linestyle. 0 for
Number between 0
Transparency completely [transparency=95]
and 100
opaque and
100 for
completely
transparent.

Whether or not
the plot is
Visible Yes, No [visible=no]
visible by
default.

The width of
Width Positive number [width=2]
the plot line.

Functions
BullScript contains many functions that perform more complex operations. An example of
such a function is the max function, which gives the maximum of two numbers. Functions
are run by placing their name followed by parenthesis that contain the parameters being

16
Learning BullScript

given to the function to operate on. So to find the maximum of two numbers, one could
write the formula max(4,C). This would evaluate to 4 if the close price is less than 4,
and to the close price otherwise.
Functions accept a certain number of parameters. It’s not possible to write max(5) for
instance, since finding the maximum of one number doesn’t make sense. The square root
function, sqrt, must have only one parameter though, since finding a square root is
performed on one number. Some functions, such as the max function, can take a varying
number of parameters. Max must be given at least two parameters, but it could be given
three or four parameters, in which case it will calculate the maximum of all the numbers it
is given.
There are also function equivalents to the mathematical operators, for example add does
the same thing as the + operator. The formula add(C,5) is equivalent to C+5.
The result of one formula may be used as a parameter for another formula. For example,
it’s possible to write max(add(C,5),8) to find the maximum of C+5 and 8.
If a formula does not require any parameters at all, such as the atr function, then it may
be written with an empty parenthesis after it, like atr(), or the parenthesis may simply
be omitted.
Certain functions take special parameters that are not numbers. An example of such a
function is the ma function, which calculates moving averages. Its third paramter specifies
the type of moving average being calculated, and may have parameters such as simple,
exponential, or variable, to indicate the type of moving average calculated. For
instance, ma(C,14,exponential) calculates a 14-day moving average of the close
price.

Candle Patterns
BullScript contains a number of functions designed to autmatically detect candlestick
patterns. These functions can typically be called without any parameters, and will return 1
(true) when the candle patterns is present, and 0 (false) at all other times.
Specifically, the patterns will return true when the pattern is present and the last bar of the
pattern is the bar being processed.
A list of candle pattern functions is as follows:

Name

Abandoned Baby Bottom

Abandoned Baby Top

17
Getting Started with BullScript

Bearish Counter Attack

Bear Harami

Bear Harami Cross

Bearish Separating Line

Big Black

Big White

Black

Bull Harami

Bull Harami Cross

Bullish Counter Attack

Bullish Separating Line

Dark Cloud Cover

Doji

Doji Star

Downward Gapping Tasuki

Dragonfly Doji

Engulfing Bear

Engulfing Bull

Falling Three

Falling Window

Gravestone Doji

18
Learning BullScript

Hammer

Hanging Man

Inverted Hammer

Long Legged Doji

Long Lower Shadow

Long Upper Shadow

Morning Doji Star

Morning Star

Rising Window

Rising three

Shaven Bottom

Shaven Head

Shooting Star

Three Black Crows

Three White Soldiers

Tri-Star Top

Tri-Star Bottom

Tweezer Bottoms

Tweezer Tops

Upside Gap Two Crows

Upward Gapping Tasuki

19
Getting Started with BullScript

White

Displaying Text
BullCharts normally draws formulas as a chart line. However, it is possible to create
formulas that show text on a chart.
The key components to drawing text are:

• Determining what the text should be


• Determining what day(s) to show the text on
• Determining what how high on the chart to show the text

To draw text, set the LineStyle attribute to Text. Then two calculations need to be
provided. The first determines the text (if any) to be drawn for that bar, and the second
determines the y-position of the text (in dollars, or what ever unit the y-axis is using). If
either of these calculations returns undefined then no text is drawn.
Calculations must appear in pairs until the linestyle is changed to something else, or the
end of the script is reached.
Other aspects of text can also be controlled using the Font, Colour, FontStyle, FontSize
and TextAlign attributes. Refer to the help pages on these attributes to learn more.
When creating text (often called strings) you specify some text directly by enclosing it in
quote marks "such as this". The BullScript editor will colour these Aqua. Strings
can joined together by using the + operator. Remember to include spaces when joining
strings. So "This" + " and that" will give "This and that". Numeric values can
also be joined to strings. For example "The price is "+Close might show "The
price is 3.75".
Strings can be used in conjunction with some other BullScripts such as the if statement.
The code if(C>O,"Close","Open")+" is bigger" will either say "Close is
bigger" or "Open is bigger" depending on their values.

Example 1
The following BullScript will write the word 'Hello' above the high price of the 20th bar
on the chart.
[target=Price]
[linestyle=Text; textalign=Above,Center]
[font="Times New Roman"; fontsize=30; fontstyle=Bold]

20
Learning BullScript

if(barnumber=20,"Hello",undefined);
High;

Example 2
This chart can be created with the script shown below.

[target=Price]
size := input("Zig zag size",4,0);
z := zigzag(Close,size,%);
ispeak := z>hist(z,1) and z>future(z,1);
istrough := z<hist(z,1) and z<future(z,1);

[linestyle=Solid; color=Red]
z;

[color=Blue]
[linestyle=Text; textalign=Above,Center]
if(isPeak, "Peak at " + z, undefined);
High;

[linestyle=Text; textalign=Below,Center]
if(isTrough, "Trough at " + z, undefined);

21
Getting Started with BullScript

Low;

See Also
Attributes | Colour | Font | FontStyle | FontSize | LineStyle | TextAlign

22
Function Reference
Function Reference
The following pages list the functions that are built into BullScript. Each function
describes any arguments, gives a description of what the function itself does, and provides
an example of how to use the function.
Functions are grouped into categories, then listed alphabetically within each category.

General
General Functions
This section describes basic BullScript functions used to make decisions, refer to other
data bars, call other scripts and input data.

AllFalse
Usage
ALLFALSE(EXPR, N)

expr

A yes/no (boolean) expression that is evaluated every bar.

The number of bars over which expr is evaluated.


Description
Returns ‘true’ if the yes/no (boolean) expression expr has been false for every bar in the
last n bars.
Example
allfalse(CLOSE>OPEN,10)
See Also
AllTrue | AnyFalse | AnyTrue

23
Getting Started with BullScript

AllTrue
Usage
ALLTRUE(EXPR, N)

expr

A yes/no (boolean) expression that is evaluated every bar.

The number of bars over which expr is evaluated.


Description
Returns ‘true’ if the yes/no (boolean) expression expr has been true for every bar in the
last N bars.
Example
alltrue(CLOSE>OPEN,10)
See Also
AllFalse | AnyFalse | AnyTrue

AnyFalse
Usage
ANYFALSE(EXPR, N)

expr

A yes/no (boolean) expression that is evaluated every bar.

The number of bars over which expr is evaluated.


Description
Returns ‘true’ if the yes/no (boolean) expression expr has been false for any bar in the last
n bars. Note: This is equivalent to not alltrue(expr,n).
Example
anyfalse(CLOSE>OPEN,10)

24
Function Reference

See Also
AllFalse | AllTrue | AnyTrue

AnyTrue
Usage
ANYTRUE(EXPR, N)
ALERT(EXPR, N)

expr

A yes/no (boolean) expression that is evaluated every bar.

The number of bars over which expr is evaluated.


Description
Returns ‘true’ if the yes/no (boolean) expression expr has been true for any bar in the last
n bars. Note: This is equivalent to not allfalse(expr,n).
Example
anytrue(cross(ma(C,14),C),5) will return 1 if the 14- period simple moving
average of the close price has crossed over the close price anytime in the last 5 bars.
See Also
AllFalse | AllTrue | AnyFalse

BarsSince
Usage
BARSSINCE(EXPR)

An expression that evaluates to true or false.


Description
Returns the number of bars since expr was true.
Example
barssince(open>close)

25
Getting Started with BullScript

Expression
Usage
EXPRESSION([MESSAGE[,DEFAULT]])

message

A description for the expression parameter.

default

One of Open, High, Low, Close, Volume, Value, Trades.


Description
Allows the current formula to take an expression as a parameter, and returns that
expression. If the formula is being run as an indicator, message will be displayed in a
dialog, and selection of the expression to use will be allowed. Default sets what the
default expression in the dropdown will be.
Example
a := expression("Enter the expression to run the formula
over");
b := expression("Select field to use as stop level", Low);
See Also
Input | Param

FirstValue
Usage
FIRSTVALUE(EXPR)

expr

The data to consider. eg Close.


Description
Returns the first defined value that expr takes.
Example
100*C/firstvalue(C) calculates a simple relative performance indicator.

26
Function Reference

Formula
Usage
FORMULA(NAME[,ARG1,ARGn])

name

The name or alias of the formula to call

args

Values for any expressions or inputs to pass to the


formula.
Description
Evaluates the formula given in name, with the given parameters passed to the formula and
returns the result.
Example
formula("My Indicator",8)
See Also
Referencing Other Formulae

Future
Usage
FUTURE(EXPR,N)

expr

An expression that will be calculated n bars ahead from


now.

The number of bars to look ahead.


Description
Returns the value of expr, n bars from now. Unfortunately, undefined if there is
insufficient data. Equivalent to the MetaStock Ref function - though use hist instead.
Example
future(C,1) returns the close for the following bar.

27
Getting Started with BullScript

See Also
Hist, Future and Previous | Hist

Hist
Usage
HIST(EXPR,N)

expr

An expression that will be calculated n bars previous.

The number of bars to look ahead.


Description
Returns the value of expr, as at n bars ago. Equivalent to the MetaStock Ref function,
except the value of n is negated in MetaStock.
The hist function requires n days of historical data to calculate.
Example
C-hist(C,14) returns the change over the last 14 bars.
See Also
Hist, Future and Previous | Future | Previous

If
Usage
IF(TEST,EXPR1,EXPR2)

TEST

An expression that should return either 'true' or 'false'.

expr1

Will be evaluated and returned if test returns true.

expr2

Will be evaluated and returned if test returns false.

28
Function Reference

Description
Returns expr1 if test is true, otherwise returns expr2. The if function can also be used test
for multiple cases by embedding consecutive ifs. Refer to the examples.
Example
if(OPEN > CLOSE, OPEN, CLOSE) returns the greater of open and close. Note: In
practice the max function would be used for this calculation.
if(CLOSE => 5 AND CLOSE <= 10, 500, 0) returns 500 if the closing price is
between 5 and 10 inclusive, otherwise it returns 0.
if(Volume >= 1000000 OR Trades >= 5000, 1, 0) returns 1 if either
Volume is at least one million, or trades if greater than 5000, otherwise 0 is returned. Note
that if both volume and trades are greater than their respective levels then 1 is still
returned. This is called an inclusive OR.
if(C > hist(H,1), "Above", if(C < hist(L,1), "Below",
"Within"))
This example returns the text Above, Below or Within to indicate how todays close relates
to yesterdays range. Note that a second if function has been put inside the first one. It is
said to be nested. If the close is not above, then it moves on to test for below and within.
if(condition1, result1,
if(condition2, result2,
if(condition3, result3,
if(condition4, result4,
result5))))
This example shows an convenient way to lay out nested if functions (remember that
BullScript ignores line-ends). condition1 is checked first. It could be Close>Open, for
example, or anything else that returns true/false. If condition1 returns true, then result1 is
immediately returned. Otherwise, it moves on to condition2. If that is true, then result2 is
returned, and so on. If none of the conditions are met then the value result5 is returned.
Note that the number of brackets on the last line matches the number of if statements.
In the above two examples, if has always been nested in the third parameter. It it also
possible to nest it in the second or first, but these are generally not recommended as it will
make the script more confusing to understand.

Input
Usage
INPUT(MESSAGE[,DEFAULT,MINIMUM,MAXIMUM])

message

A description for the input parameter.

29
Getting Started with BullScript

default

The default value for this parameter.

minimum

The minimum allowable value for this parameter.

maximum

The maximum allowable value for this parameter.


Description
Allows the current formula to take a number as a parameter, and returns that number. If
the formula is being run as an indicator, message will be displayed in a dialog, and
selection of the expression to use will be allowed. Default is the value that will be used if
none is given, and minimum and maximum are the minimum and maximum allowed
values.
Example
n := input("Enter the length of the moving
average",14,7,52); ma(C,n,SIMPLE);
See Also
Expression | Param

InputMA
Usage
INPUTMA(MESSAGE[,DEFAULT])

message

A description for the input parameter.

default

The default value for this parameter. See the Ma function


for a list of allowable values.
Description
Allows the input of a moving average method, which can them be used in a moving
average later. See the moving average topic for a list of allowable values.

30
Function Reference

Example
n := input("Enter the moving average length",14,7,52);
method := inputma("Enter the moving average method",SIMPLE);
ma(C,n,method);
See Also
Input | Ma function

InputROC
Usage
INPUTROC(MESSAGE[,DEFAULT])

message

A description for the input parameter.

default

The default value for this parameter. May be either


Percent, or Points.
Description
Allows the input of a rate of change method, which can them be used in a rate of change
function later. See the rate of change topic for a list of allowable values.
Example
n := input("Enter the ROC length",14,7,52);
method := inputroc("Enter the ROC method",PERCENT);
roc(C,n,method);
See Also
Input | ROC function

Param
Usage
PARAM([MESSAGE,DEFAULT,MINIMUM,MAXIMUM])

message

A description for the input parameter.

default

31
Getting Started with BullScript

The default value for this parameter.

minimum

The minimum allowable value for this parameter.

maximum

The maximum allowable value for this parameter.


Description
Allows the current formula to take a dynamic number as a parameter, and returns that
number. If the formula is being run as an indicator, message will be displayed in a dialog,
and selection of the expression to use will be allowed. Default is the value that will be
used if none is given, and minimum and maximum are the minimum and maximum
allowed values.
Param differs from input in that param accepts a number that may change, for
example a Close price. Input accepts only numbers that do not change, and thus are
useful for giving to functions that require an unchanging number.
Example
CLOSE*param("Enter the amount to multiply close by")
See Also
Expression | Input

Previous
Usage
PREVIOUS([SEED[,N]])
PREV([SEED[,N]])

seed

The initial value if previous bars are available.

The number of bars to look back.

32
Function Reference

Description
Calculates the value of the current formula as it was n bars ago, or returns seed if there are
less than n bars available. If n is not given, 1 is used. If seed is not given, 0 is used. An
expression (eg Close) may be used for seed.
Example
0.20*close + 0.80*previous(close) calculates an exponential moving
average.
See Also
Hist, Future and Previous | Hist

ValueWhen
Usage
VALUEWHEN(N,EXPR1,EXPR2)

The number of times counted back. Eg: Use 1 to find the


most recent time expr1 was true.

expr1

An expression that returns true/false. This is the condition


that is checked.

expr2

The result to be returned.


Description
Calculates the value of expr2, as at the nth most recent time that expr1 was true.
Example
valuewhen(4, cross(C,ma(C,14)), typical) returns the typical price as at
the 4th most recent time that the close price crossed over its 14-period simple moving
average.

Wait
Usage
WAIT(EXPR,N)

33
Getting Started with BullScript

expr

This data will be the result of the wait function.

Number of additional ticks to wait before generating


results.
Description
Waits n additional days before returning the result of expr. Useful when trying to exactly
copy an indicator that does not start immediately. Some of Wilder’s indicators behave this
way.
Wait can also be passed a negative value, indicating that results should be returned early.
This is useful where BullScript is not able to calculate the data requirements exactly (as
BullScript calculates data requirements statically).
Example
wait(sum(CLOSE,10),2) will return the same result as sum(CLOSE,10), except
that the former starts on the 12th bar instead of the 10th.
if(barnumber < 20, ma(C,5), ma(C,20)) will not start until the 20th day
because of the rules BullScript uses when calculating data requirements. But by putting it
in wait(...,-15) it will start on the 5th day as expected.

Mathematical
Mathematical Functions
This section lists a variety of mathematical functions including statistical functions,
trigonometry, and rounding.

Absolute Value
Usage
ABS(A)

A number.
Description
Finds the absolute value of a. That is, the value of a without regard to sign.

34
Function Reference

Example
abs(4) is 4, and abs(-4) is 4.

Add
Usage
ADD(n1,n2...)

n1, n2...

Values to be added together


Description
Adds all its parameters together. This is equivalent to n1+n2. Multiple parameters can be
passed in.
Example
add(3,2) returns 5.
add(3,2,5,2) returns 12.
See Also
Operators | Sum

Arc Tangent
Usage
ATAN(ANGLE)

angle

An angle, specified in degrees.


Description
Calculates the arc tangent of angle degrees.
Example
atan(8.4)
See Also
Cosine | Sine

35
Getting Started with BullScript

Ceiling
Usage
CEILING(N)

A number.
Description
Calculates the smallest integer which is greater than or equal to n.
Example
ceiling(4.2) returns 5.
ceiling(-3.6) returns -3.
See Also
Floor | Frac | Int | Round

Correlation
Usage
CORREL(EXPR1,EXPR2,N)

expr1

The first data set.

expr2

The second data set.

Number of periods used in calculation.


Description
Calculates the correlation between expr1 and expr2 over n periods.
Example
correl(V, C-hist(C,1), 21)

36
Function Reference

Cosine
Usage
COS(ANGLE)

angle

An angle, specified in degrees.


Description
Returns the cosine of angle degrees.
Example
cos(60) returns 0.5
See Also
Arc Tangent | Cosine

Divide
Usage
DIV(A,B)

The numerator.

The denominator.
Description
Calculates a divided by b.
Example
div(8,2) returns 4.
See Also
Mod | Operators

Exponent
Usage
EXP(POWER)

37
Getting Started with BullScript

power

The power that e is raised to.


Description
Raises e (approximately 2.718) to the power of power.
Example
exp(5)
See Also
Log

Fibonacci
Usage
FIB(N)

The nth fibonacci number is returned.


Description
Returns the nth fibonacci number. Fibonacci numbers are a sequence of numbers were
each number is equal to the sum of the previous two. The first few Fibonacci numbers are:
1,1,2,3,5,8,13,21...
Example
fib(1) returns 1.
fib(2) returns 1.
fib(3) returns 2.
fib(4) returns 3.

Floor
Usage
FLOOR(N)

A number.
Description
Calculates the greatest integer which is smaller than or equal n.

38
Function Reference

Example
floor(4.2) returns 4.
floor(-3.6) returns -4.
See Also
Ceiling | Frac | Int | Round

Fractional Part
Usage
FRAC(N)

A number.
Description
Returns the fractional portion of n.
Example
frac(4.87) returns 0.87
See Also
Ceiling | Floor | Int | Round

Int
Usage
INT(N)

A number.
Description
Returns the integer portion of n.
Example
int(7.8) returns 7
int(-7.8) returns -7
See Also
Ceiling | Floor | Frac | Round

39
Getting Started with BullScript

Linear Regression
Usage
LINEARREG(EXPR,N)

expr

Data to be processed.

Number of periods sampled.


Description
Calculates the Linear Regression indicator for expr over n periods.
Example
linearreg(C,21)
See Also
LinRegSlope

Linear Regression Slope


Usage
LINREGSLOPE(EXPR,N)

Number of periods sampled.


Description
Calculates the Linear Regression Slope indicator for expr over n periods.
Example
linregslope(C,21)
See Also
LinearReg

Logarithm
Usage
LOG(N[,BASE])

40
Function Reference

A number.

base

The log base that will be used, or e if omitted.


Description
Calculates the base logarithm of n. If base is not given, then the natural logarithm, e, of n
is calculated.
Example
log(Volume)
log(Volume,10)
See Also
Exp

Max
Usage
MAX(N1,N2...)

n1, n2

A list of numbers.
Description
Returns the largest value currently assumed by any of its parameters.
Max should not be confused with the Highest function, which returns the largest value a
single parameter has assumed over a number of bars.
Example
max(2,5,4) is 5.
max(open,close) is the greater of the open and close price for the current bar.
highest(close,5) is the largest value of close over the last 5 days.
max(expr1, 5) This example uses the min function to put an lower limit on the value
returned by expr1. If expr1 is greater than 5, then expr1 will be returned unchanged. But if
it's less 5, then 5 is returned.
min(max(expr1,0),100) The above technique can be used in this way to restrict a
result to a range. In this example, expr1 is cropped to return a result between 0 and 100.

41
Getting Started with BullScript

See Also
Highest | Lowest | Min

Min
Usage
MIN(N1,N2...)

n1, n2

A list of numbers.
Description
Selects the smallest value currently assumed by any of its parameters.
Min should not be confused with the Lowest function, which returns the smallest value a
single parameter has assumed over a number of bars.
Example
min(2,5,4) is 2.
min(open,close) is the smaller of the open and close price for the current bar.
lowest(close,5) is the smaller value of close over the last 5 days.
min(expr1, 10) This example uses the min function to put an upper limit on the
value returned by expr1. If expr1 is less than 10, then expr1 will be returned unchanged.
But if it's greater than 10, then 10 is returned.
min(max(expr1,0),100) The above technique can be used in this way to restrict a
result to a range. In this example, expr1 is cropped to return a result between 0 and 100.
See Also
Highest | Lowest | Max

Modulus
Usage
MOD(A,B)

The number being divided.

The number dividing.

42
Function Reference

Description
Calculates a modulo b. That is, the remainder of a divided by b.
Example
mod(21,8) returns 5.
See Also
Divide

Multiply
Usage
MUL(N1,N2...)

n1,n2..

A list of numbers to be multiplied.


Description
Multiplies it's parameters together. Equivalent to n1*n2
Example
mul(4,3) returns 12.
mul(4,2,3) returns 24.
See Also
Operators

Negate
Usage
NEG(N)

The number to be negated.


Description
Returns the negative of n. Equivalent to -(n)
Example
neg(8) returns -8.
neg(-8) returns 8.

43
Getting Started with BullScript

See Also
Operators

Pi
Usage
PI

Description
Returns 3.14159265358979, the mathematical constant π. π is the ratio of a circle's
circumference to its diameter.

Power
Usage
POWER(A,B)

The base.

The exponent.
Description
Raises a to the power of b. Equivalent to a^b.
Example
power(5,2) returns 25.
See Also
Operators

Round
Usage
ROUND(A[,N])

A number.

44
Function Reference

Number of decimal places, zero if omitted.


Description
Rounds a to n decimal places, or to the nearest integer if n is not given.
Example
round(4) returns 4
round(4.2) returns 4
round(4.5) returns 5
round(4.7) returns 5
round(-8.2) returns -8
round(-8.7) returns -9
round(4.56,1) returns 4.6

See Also
Ceiling | Floor | Frac | Int

Sine
Usage
SIN(ANGLE)

angle

An angle, specified in degrees.


Description
Returns the sine of angle degrees.
Example
cos(30) returns 0.5
See Also
Arc Tangent | Sine

Square Root
Usage
SQRT(N)

45
Getting Started with BullScript

A number.
Description
Finds the square root of n. That is, it find a number that gives n when it is squared.
Example
sqrt(16) returns 4.

Standard Deviation
Usage
STDEV(EXPR,N)

expr

The data being evaluated.

Number of periods.
Description
Finds the standard deviation of expr over the last n periods.
Example
stdev(C,14)
See Also
Standard Error

Standard Error
Usage
STEYX(EXPR,N)

expr

The data being evaluated.

Number of periods.

46
Function Reference

Description
Finds the standard error of expr over the last n periods.
Example
steyx(C,14)
See Also
Standard Deviation

Subtract
Usage
SUB(A,B)

n1, n2...

Values to be added together


Description
Calculates b subtracted from a. Equivalent to a-b.
Example
sub(6,2) returns 4.
See Also
Operators

Sum
Usage
SUM(EXPR[,N])

expr

Data to be summed.

Number of periods to be summed. Or if not given the


cumulative sum for the dataset so far.
Description
Calculates the rolling sum of expr over the last n periods, or over the entire dataset if n is
omitted.

47
Getting Started with BullScript

The sum function requires n-1 days of historical data to calculate.


Example
sum(CLOSE,14)/14 finds the average of the close price over the last 14 periods (and
is thus equivalent to ma(C,14,simple)).
See Also
Add

Trendline
Usage
TRENDLINE(EXPRY, EXPRX, EXTR, EXTL, DIR)

exprY

An expression that specifies the 'y coordinate' of the


trendline, for example Low.

exprX

An expression that returns true on certain days to mark


off 'x coordinates'.

extR

Extend the trendline to the right. 1=true, 0=false.

extL

Extend the trendline to the left. 1=true, 0=false.

dir

The required slope of the rendline. -1=down sloping,


0=either, 1=up sloping
Description
Returns a set of values that will appear as a trendline. The last two times that exprX return
true mark off the start and end of the trendline period. The values of exprY at these two
locations will be used to fix the start and end points.
Several additional parameters allow extra configuration of the line - such as whether it
will only yield values between the two points, or if the line will be extended. Undefined
will be returned for intervals outside of the range if the line is not extended.

48
Function Reference

The dir parameter allows constraints to be placed on the line such as "only draw if the
trend is sloping up (positive gradient) or down (negative gradient).
Example
z := zigzag(C,8,%);
tro := z<future(z,1) and z<hist(z,1);
trendline(L, tro, 1, 0, 1);
This example calculates a zigzag line with an 8% reversal requirement. The variable tro
evaluates to true whenever the zigzag has reached a trough. The trendline function as used
here will draw a trendline through the last two troughs of the zig zag. It will contine to the
right only, and it will only appear if the trendline is upward sloping.

Candle Pattern
Candle Pattern Functions
This section describes a number of functions built into BullScript designed to identify
candle patterns. Unless otherwise stated, each function returns true if the pattern is
completed on the current bar.
It is important to realise that all of our reversal candle patterns must be preceeded by an
up or down trend. The WebLink definition of a trend follows that given in the Securities
Institute Technical Analysis course notes section 3, page 9.
This states briefly that:

• An uptrend is a succession of higher highs and higher lows. An uptrend is only


ended when a candle with a lower high AND a lower low than the previous
candle is encountered.
• A downtrend is a succession of lower lows and lower highs. A downtrend is only
ended when a candle with a higher high AND higher low than the previous andle
is encountered.

Bearish Harami
Usage
BEARHARAMI

Description
A small real body of either colour which is contained within the prior large white body.
This is a top reversal pattern and as such should be preceded by an uptrend.

49
Getting Started with BullScript

Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p82.
Example

See Also
Bear Harami Cross | Bull Harami | Bull Harami Cross | Candle Patterns

Bearish Harami Cross


Usage
BEARHARAMICROSS

Description
A Doji which is contained within the prior large white body.
This is a top reversal pattern and as such should be preceded by an uptrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p83.
Example

See Also
Bear Harami | Bull Harami | Bull Harami Cross | Candle Patterns | Doji

Big Black
Usage
BIGBLACK

Description
A large black body, where the open is near the high, and the close is near the low.

50
Function Reference

Example

See Also
Big White | Candle Patterns

Big White
Usage
BIGWHITE

Description
A large white body, where the open is near the low, and the close is near the high.
Example

See Also
Big Black | Candle Patterns

Black Body
Usage
BLACK

Description
A candlestick which has a black body.
Example

See Also
White Body | Candle Patterns

51
Getting Started with BullScript

Bull Harami
Usage
BULLHARAMI

Description
A small real body of either colour which is contained within the prior large black body.
This is a bottom reversal pattern and as such should be preceded by an downtrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p82.
Example

See Also
Bear Harami | Bear Harami Cross | Bull Harami Cross | Candle Patterns

Bullish Harami Cross


Usage
BULLHARAMICROSS

Description
A Doji which is contained within the prior large black body.
This is a bottom reversal pattern and as such should be preceded by a downtrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p83.
Example

See Also
Bear Harami | Bear Harami Cross | Bull Harami | Candle Patterns | Doji

52
Function Reference

Doji
Usage
DOJI

Description
A candlestick where the open and close are the same. Doji can be powerful reversal lines
when preceded by a trend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p155.
Example

See Also
Candle Patterns | Doji Star

Doji Star
Usage
DOJISTAR

Description
A Doji which gaps above a white candlestick, or below a black candlestick.
Example

See Also
Candle Patterns | Doji | Evening Doji Star | Morning Doji Star | Shooting Star

Engulfing Bear
Usage
ENGULFINGBEAR

Description
A large black real body that contains a small real white body that precedes it. Also known
as the Bearish Engulfing Pattern.

53
Getting Started with BullScript

Example

See Also
Candle Patterns | Engulfing Bull

Engulfing Bull
Usage
ENGULFINGBULL

Description
A large white real body that contains a small real black body that precedes it. Also known
as the Bullish Engulfing Pattern.
This is a bottom reversal pattern and as such should be preceded by an downtrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p42.
Example

See Also
Candle Patterns | Engulfing Bear

Falling Window
Usage
FALLINGWINDOW

Description
A gap between the low of the first candlestick and the high of the second candlestick.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p126.

54
Function Reference

Example

See Also
Candle Patterns | Rising Window

Gravestone Doji
Usage
GRAVESTONEDOJI

Description
A Doji where there is no lower shadow and an extremely long upper shadow.
Gravestone doji are used as a top reversal line and as such should be preceded by an
uptrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p162.
Example

See Also
Candle Patterns | Doji

Hammer
Usage
HAMMER

Description
A small real body of either colour with a lower shadow at least twice the real body size,
which closes nears the high.
In practice there is some latitude for what constitutes 'a small real body'. The most
important aspect of this pattern is the long lower shadow with a minimal upper shadow.
The Hammer is a bottom reversal pattern and as such should be preceded by a downtrend.

55
Getting Started with BullScript

Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p34.
Example

See Also
Candle Patterns | Hanging Man | Inverted Hammer

Hanging Man
Usage
HANGINGMAN

Description
A small real body of either colour with a lower shadow at least twice the real body size,
which closes nears the high. The main difference between this pattern and the Hammer is
the prior trend direction. The Hammer requires a prior uptrend but the Hanging man
requres a prior downtrend.
Note that because of the bullish nature of the long lower shadow additional confirmation
may be required before this pattern is considered bearish.
The Hanging Man is a top reversal pattern and as such should be preceded by an uptrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p39.
Example

See Also
Candle Patterns | Hammer

Inverted Hammer
Usage
INVHAMMER

Description
An upside-down Hammer that is either white or black.

56
Function Reference

This is a bottom reversal line and as such should be preceded by a decline.


Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p74.
Example

See Also
Candle Patterns | Hammer

Long Legged Doji


Usage
LONGLEGGEDDOJI

Description
A Doji that has particularly long upper and lower shadows.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p161.
Example

See Also
Candle Patterns | Doji

Long Lower Shadow


Usage
LONGLOWERSHADOW

Description
A candlestick, either black or white, that has a lower shadow that is more than twice as
long as the upper shadow and body.

57
Getting Started with BullScript

Example

See Also
Candle Patterns | Long Upper Shadow

Long Upper Shadow


Usage
LONGUPPERSHADOW

Description
A candlestick, either black or white, that has an upper shadow that is more than twice as
long as the lower shadow and body.
Example

See Also
Candle Patterns | Long Lower Shadow

Morning Doji Star


Usage
MORNINGDOJISTAR

Description
A Morning Star where the second candlestick is a Doji.
This is a bottom reversal pattern and as such should be preceded by an downtrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p70.

58
Function Reference

Example

See Also
Candle Patterns | Doji | Doji Star | Evening Doji Star | Morning Star

Morning Star
Usage
MORNINGSTAR

Description
A large black candlestick followed by a small real body of either colour that gaps down
from the previous candles real body. This is followed by a third candlestick that is white
and has a close higher than the half way point of the first candlestick's real body.
The ideal morning star pattern's third candle will gap above the preceeding candle's small
real body but in practice (as described by Nison) this is somewhat rare. We specifically
allow the case of the third candle engulfing the second to also satisfy the morning star
pattern.
This is a bottom reversal pattern and as such should be preceded by an downtrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p62.
Example

See Also
Candle Patterns | Evening Star | Morning Doji Star

Rising Window
Usage
RISINGWINDOW

59
Getting Started with BullScript

Description
A gap between the high of the first candlestick and the low of the second candlestick.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p126.
Example

See Also
Candle Patterns | Falling Window

Shaven Bottom
Usage
SHAVENBOTTOM

Description
A candlestick, either white or black, which has no lower shadow.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p25.
Example

See Also
Candle Patterns | Shaven Head

Shaven Head
Usage
SHAVENHEAD

Description
A candlestick, either white or black, which has no upper shadow.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p85.

60
Function Reference

Example

See Also
Candle Patterns | Shaven Bottom

Shooting Star
Usage
SHOOTINGSTAR

Description
A small real body that closes near the bottom of its range and has a long upper shadow.
There must be a real body gap up from the previous sessions candle.
This is a top reversal line and as such should be preceded by a rally.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p74.
Example

See Also
Candle Patterns | Doji Star

Three Black Crows


Usage
THREEBLACKCROWS

Description
Three long black candlesticks that each have lower close prices than the last. They
generally close at or near their low prices.
This is a top reversal pattern and as such should be preceded by an uptrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p97.

61
Getting Started with BullScript

Example

See Also
Candle Patterns | Three White Soldiers

Three White Soldiers


Usage
THREEWHITESOLDIERS

Description
Three long white candlesticks that each have higher close prices than the last. They
generally close at or near their high prices.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p99.
Example

See Also
Candle Patterns | Three Black Crows

Tweezer Bottoms
Usage
TWEEZERBOTTOMS

Description
A large black candle followed by a candle with the same low.
Tweezer Bottoms are a bottom reversal pattern and as such should be preceded by a
downtrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p87.

62
Function Reference

Example

See Also
Candle Patterns | Tweezer Tops

Tweezer Tops
Usage
TWEEZERTOPS

Description
A large white candle followed by a candle with the same high.
Tweezer Tops are a top reversal pattern and as such should be preceded by an uptrend.
Reference
Japanese Candlestick Charting Techniques Second Edition - Steve Nison, p87.
Example

See Also
Candle Patterns | Tweezer Bottoms

White Body
Usage
WHITE

Description
A white candlestick. That is, where the close was higher than the open.
Example

63
Getting Started with BullScript

See Also
Black Body | Candle Patterns

Pattern Recognition
Pattern Recognition Functions
This section lists functions used to identify simple patterns such as gaps and crossovers.
Also refer to the candle patterns section for candle specific fuctions.

Cross
Usage
CROSS(EXPR1,EXPR2)

expr1

First data source for testing crosses.

expr1

Second data source for testing crosses.


Description
Returns true if expr1 crosses higher than expr2 on the current bar, and false otherwise. To
determine if a cross happened in the other direction, reverse the two parameters.
Example
cross(C, ma(C,14)) returns true when close breaks above the 14 day moving
average.
cross(ma(C,14), C) returns true when close pushes below the 14 day moving
average.

GapDown
Usage
GAPDOWN()

Description
Returns 1 for any bar where a gap down occurs, and 0 otherwise. A gap down occurs if the
previous bar’s low is greater than this bar’s high.

64
Function Reference

See Also
GapUp

GapUp
Usage
GAPUP()

Description
Returns 1 for any bar where a gap up occurs, and 0 otherwise. A gap up occurs if the
previous bar’s high is less than this bar’s low.
See Also
GapDown

Inside
Usage
INSIDE()

Description
Returns 1 if the current bar is ‘inside’ the previous one, and 0 otherwise. A bar is inside if
its high is less than the previous bar's high, and its low is greater than the previous bar's
low.
See Also
Outside

Outside
Usage
OUTSIDE()

Description
Returns 1 if the current bar is ‘outside’ the previous one, and 0 otherwise. A bar is outside
if its high is greater than the previous bar’s high, and its low is less than the previous bar’s
low.
See Also
Inside

65
Getting Started with BullScript

Date and Time


Date and Time Functions
This section explains how to work with functions that operate on dates and times.
Functions include the ability to input a date as a parameter, and extract certain parts of the
date, such as month.

Date
Usage
DATE(YEAR,[MONTH,[DAY,[HOUR,[MINUTE,[SECOND]]]]])

year

The year as a 4 digit number.

month

A value between 1 and 12. Defaults to 1 if not given.

day

A value between 1 and 31. Defaults to 1 if not given.

hour

A value between 0 and 23. Defaults to 0 if not given.

minute

A value between 0 and 59. Defaults to 0 if not given.

second

A value between 0 and 59. Defaults to 0 if not given.


Description
Returns a date value given the year, month, day, hour, minute, and second specified. If
second, minute, or hour are not specified, 0 will be used. If month or day are not specified,
1 will be used.
See Also
Year | Month | DayOfMonth | Hour | Minute | Second

66
Function Reference

DayOfMonth
Usage
DAYOFMONTH([DATEVALUE])

datevalue

The date that will be evaluated.


Description
Returns the day of the month of the given date value, or of the current bar if datevalue is
not specified.
See Also
Date | Year | Month | Hour | Minute | Second

Hour
Usage
HOUR([DATEVALUE])

datevalue

The date that will be evaluated.


Description
Returns the hour of the given date value, or of the current bar if datevalue is not specified.
See Also
Date | Year | Month | DayOfMonth | Minute | Second

InputDate
Usage
INPUTDATE([MESSAGE,[DEFAULT]])

message

A description for the input parameter.

default

The default date value for this parameter.

67
Getting Started with BullScript

Description
Allows input of a date from the user or another formula using this formula. Will display
message as a prompt to the user. Default will be used by default, or if default is not
specified then todays date will be used by default.
Example
{without a default}
d1 := inputdate("Trade Date");
{with a default}
d2 := inputdate("Trade Date", Date(2004,11,30));
See Also
Date | OnOrSkipped

Minute
Usage
MINUTE([DATEVALUE])

datevalue

The date that will be evaluated.


Description
Returns the minute of the given date value, or of the current bar if datevalue is not
specified.
See Also
Date | Year | Month | DayOfMonth | Hour | Second

Month
Usage
MONTH([DATEVALUE])

datevalue

The date that will be evaluated.


Description
Returns the month of the given date value, or of the current bar if datevalue is not
specified. 1 for January, 2 for February, and so forth.

68
Function Reference

See Also
Date | Year | DayOfMonth | Hour | Minute | Second

Now
Usage
NOW()

Description
Returns the date value of the current bar.

Second
Usage
SECOND([DATEVALUE])

datevalue

The date that will be evaluated.


Description
Returns the second of the given date value, or of the current bar if datevalue is not
specified.
See Also
Date | Year | Month | DayOfMonth | Hour | Minute

Year
Usage
YEAR([DATEVALUE])

datevalue

The date that will be evaluated.


Description
Returns the year of the given date value, or of the current bar if datevalue is not specified.
See Also
Date | Month | DayOfMonth | Hour | Minute | Second

69
Getting Started with BullScript

Highest/Lowest
Highest/Lowest Functions
This section lists functions specifically designed to identify the highest and lowest bar in a
range.

Highest
Usage
HIGHEST(EXPR[,N])
HHV(EXPR[,N])

expr

The expression being evaluated.

The number of bars over which expr is evaluated.


Description
Returns the highest value expr has assumed over the last n periods. If n is not given, then
it will return the highest value expr has assumed over the entire dataset. Not to be
confused with Max.
Example
highest(H,10) is the highest high value for the last 10 bars.
highest(H) is the highest high value for the entire dataset.
See Also
Lowest | Max | Min

HighestBars
Usage
HIGHESTBARS(EXPR[,N])
HHVBARS(EXPR[,N])

expr

The expression being evaluated.

70
Function Reference

The number of bars over which expr is evaluated.


Description
Returns the number of bars ago that expr was the highest it has been over the last n bars.
Or if n is not given, the number of bars ago it was at its highest for the entire dataset.
Example
highest(H,10) is the highest high value for the last 10 bars.
highest(H) is the highest high value for the entire dataset.
See Also
Highest | LowestBars

HighestSince
Usage
HIGHESTSINCE(N,EXPR1,EXPR2)

The number of times ago that expr1 was true.

expr1

An expression that evaluates to true or false.

expr2

The expression that highest will be calculated from.


Description
Returns the highest value expr2 has assumed since the nth time ago that expr1 was true.
Example
highestsince(4,cross(mov(C,7),mov(C,21)),C)
returns the highest close price that has occurred since the fourth time ago that the 7-day
simple moving average crossed the 21-day simple moving average.

HighestSinceBars
Usage
HIGHESTSINCEBARS(N,EXPR1,EXPR2)

71
Getting Started with BullScript

The number of times ago that expr1 was true.

expr1

An expression that evaluates to true or false.

expr2

The expression that highest will be calculated from.


Description
Returns the number of bars since the highest value of expr2 was assumed since the nth
time ago that expr1 was true.

Lowest
Usage
LOWEST(EXPR[,N])
LLV(EXPR[,N])

expr

The expression being evaluated.

The number of bars over which expr is evaluated.


Description
Returns the lowest value expr has assumed over the last n periods. If n is not given, then it
will return the lowest value expr has assumed over the entire dataset. Not to be confused
with Min.
Example
lowest(L,10) is the lowest low value for the last 10 bars.
lowest(L) is the lowest low value for the entire dataset.
See Also
Lowest | Max | Min

72
Function Reference

LowestBars
Usage
LOWESTBARS(EXPR[,N])
LLVBARS(EXPR[,N])

expr

The expression being evaluated.

The number of bars over which expr is evaluated.


Description
Returns the number of bars ago that expr was the lowest it has been over the last n bars.
Or if n is not given, the number of bars ago it was at its lowest for the entire dataset.
Example
lowest(H,10) is the lowest low value for the last 10 bars.
lowest(H) is the lowest low value for the entire dataset.
See Also
Lowest | HighestBars

LowestSince
Usage
LOWESTSINCE(N,EXPR1,EXPR2)

The number of times ago that expr1 was true.

expr1

An expression that evaluates to true or false.

expr2

The expression that lowest will be calculated from.


Description
Returns the lowest value expr2 has assumed since the nth time ago that expr1 was true.

73
Getting Started with BullScript

Example
lowestsince(4,cross(mov(C,7),mov(C,21)),C)
returns the lowest close price that has occurred since the fourth time ago that the 7-day
simple moving average crossed the 21-day simple moving average.

LowestSinceBars
Usage
LOWESTSINCEBARS(N,EXPR1,EXPR2)

The number of times ago that expr1 was true.

expr1

An expression that evaluates to true or false.

expr2

The expression that lowest will be calculated from.


Description
Returns the number of bars since the lowest value of expr2 was assumed since the nth
time ago that expr1 was true.

Indicator Functions
Indicator Functions
This section describes many of the indicator functions that can be used in BullScript.
Many of these indicators are written in BullScript themselves, and use the alias attribute to
make themselves available to other scripts.

Accumulation Swing Index


Usage
ASWING(LIMITMOVE)

limitmove

Limit on movement.

74
Function Reference

Description
Calculates the accumulation swing index, with the given limit on movement.
Developed by Welles Wilder, the Accumulation Swing Index compares current prices and
previous prices to illustrate the 'real' price of a security. It is the cumulative total of
another indicator also developed by Wilder, known as the Swing Index
Example
aswing(2.0)
See Also
Swing Index

Accumulation/Distribution
Usage
AD()

Description
Calculates the accumulation/distribution indicator according to this formula: sum((((C
- L) - (H - C))/(H - L))*V)
The accumulation distribution formula is an improved On Balance Volume indicator. This
indicator uses a relationship between volume and prices to estimate the strength of price
movements. If the volume is increased, there is a high probability that prices will move
up.
See Also
On Balance Volume | Chaikin Accumulation/Distribution Oscillator

Aroon Down
Usage
AROONUP(N)
AROONDOWN(N)

The number of bars used to calculate Aroon.


Description
AroonUp and AroonDown calculate the 'up' and 'down' portion respectively of the
Aroon indicator, developed by Tushar Chande, over n bars.

75
Getting Started with BullScript

Example
aroonup(24)
aroondown(24)

Average Directional Movement


Usage
ADX(N)

The number of bars used to calculate Average Directional


Movement.
Description
Calculates Wilder's Average Directional Movement indicator over n bars.
Wilder's Average Directional Movement is used to evaluate the strength of the current
trend, be it up or down. Low readings, below 20, indicate a weak trend and high readings,
above 40, indicate a strong trend. The indicator does not grade the trend as bullish or
bearish, but merely assesses the strength of the current trend.
Example
adx(14)
See Also
+DI | -DI | DX | ADXR | CSI

Average True Range


Usage
ATR(N)

The number of bars used to calculate Average True Range.


Description
Calculates the Average True Range indicator over n bars.
Average True Range is an indicator that measures commitment comparing the range
between high, low and close prices. This indicator was developed by J. Welles Wilder.
Example
atr(24)

76
Function Reference

Bollinger Bands
Usage
BBANDTOP(EXPR,N,METHOD,DEVIATIONS)
BBANDBOT(EXPR,N,METHOD,DEVIATIONS)

expr

The data that the bollinger bands will be calculated over.


Typically closing price.

The number of periods used to calculate the bands.

method

The moving average method used.

deviations

The number of standard deviations that the band will be


away from the moving average line.
Description
BBandTop and BBandBot calculate the top and bottom line respectively of the
Bollinger Band for expr over n periods, using the given number of deviations.
Example
bbandbot(C,14,S,1)

Chaikin Accumulation/Distribution Oscillator


Usage
CO()

Description
Calculates the Chaiking Accumulation/Distribution Oscillator.
The Chaikin Oscillator indicator is the difference between a 3-day exponential moving
average and a 10-day exponential moving average applied to Accumulation Distribution.
See Also
Accumulation Distribution

77
Getting Started with BullScript

Chaikin's Money Flow


Usage
CMF(N)

The number of periods to calculate the money flow over.


Description
Calculates Chakin’s Money Flow over n periods.
Chaikin Money Flow compares total volume to the closing price and the daily highs and
lows to determine how many issues are bought and sold of a particular security.
Example
cmf(14)

Chande Momentum Oscillator


Usage
CMO(EXPR,N)

expr

The data to use when calculating CMO.

The number of periods to calculate the CMO over.


Description
Calculates the Chande Momentum Oscillator for expr over n periods. The Chande
Momentum Oscillator is an advanced momentum oscillator calculated using linear
regression techniques.
Example
cmo(C,21)

Commodity Channel Index


Usage
CCI(N)

78
Function Reference

The number of periods to calculate the CCI over.


Description
Calculates the Commodity Channel Index indicator for n periods. The Commodity
Channel Index compares Prices with its moving averages.
Example
cci(21)

Commodity Selection Index


Usage
CSI(N,VALUE,MARGIN,COMMISSION)

The number of periods to calculate the CSI over.

value

The value to use

margin

The margin to use

commission

The commission to use


Description
Calculates Wilder's Commodity Selection Index over n periods, using the given value,
margin, and commission.
Example
csi(21,80,1800,20)
See Also
+DI | -DI | DX | ADX | ADXR

Double Exponential Moving Average (DEMA)


Usage
DEMA(EXPR,N)

79
Getting Started with BullScript

Number of periods.

expr

Data to calculate over.


Description
Calculates the Double Exponential Moving Average indicator.
Example
dema(close,21)
See Also
Moving Averages

Directional Movement Index


Usage
DX(N)

Number of periods.
Description
Calculates Wilder's Directional Movement Index.
Example
dx(21)
See Also
+DI | -DI | ADX | ADXR | CSI

Ease Of Movement
Usage
EMV(N,METHOD)

Number of periods.

80
Function Reference

method

Moving average method.


Description
Calculates the East of Movement over n periods, using the moving average method given
for mamethod. Ease of Movement deals with relationship between volume and price
changes.

Forecast
Usage
FORECAST(EXPR,N,AHEAD)

expr

Data to evaluate.

Number of points used in linear regression.

ahead

Number of bars to look ahead.


Description
Performs an n tick linear regression over expr, and returns the forecasted value for ahead
ticks into the future.

Forecast Oscillator
Usage
FORECASTOSC(EXPR,N)

expr

Data to evaluate.

Number of bars.

81
Getting Started with BullScript

Description
Calculates the Forecast Oscillator for expr, over n periods.
Example
forecastosc(CLOSE,21)

Fractal Dimension
Usage
FRACTALDIM(EXPR,N)

expr

The data that will be interpreted. Eg: Close.

The number of periods sampled for each calculation.


Description
Approximates the fractal dimension of expr over the last n bars. Results will be between 1
and 2. The fractal dimension is a measure of randomness, where 1.5 is maximum
randomness, and higher or lower values indicate order.
The Hurst exponent can be related to the fractal dimension as:
Hursh exponent = 2 - fractal dimension.
The algorithm used is based on the method described in "A procedure to Estimate the
Fractal Dimension of Waveforms" by Carlos Sevcik, 1998.
Example
fractaldim(C,30)

Hull ActTrade ROAR


Usage
HULLATROAR(CUTOFF,SLIQ,OLIQ)

cutoff

If the ROAR falls below this level, it will drop back to zero.
Typically 80.

sLiq

82
Function Reference

Starting liquidity. The liquidity required to start the ROAR.


Typically 3.5M.

oLiq

Ongoing liquidity. The liquidity required to sustain the


ROAR. Typically 5M.
Description
HullAtROAR calculate Alan Hulls Active Trading Rate of Annual Return indicator. Note
that there is no entry parameter for HullAtROAR. Refer to Alan Hull's Active Trading
course notes for more information.
Example
hullroar(80,3500000,5000000)
See Also
HullROAD | HullROAR

Hull ActVest ROAR


Usage
HULLROAD(ENTRY,CUTOFF,SLIQ,OLIQ)

entry

The ROAD must fall below this level to start. Typically -30.

cutoff

If the ROAD rises above below this level, it will drop back
to zero. Typically -20.

sLiq

Starting liquidity. The liquidity required to start the ROAD.


Typically 12M.

oLiq

Ongoing liquidity. The liquidity required to sustain the


ROAD. Typically 10M.

83
Getting Started with BullScript

Description
HullROAD calculate Alan Hulls Active Investing Rate of Annual Decline indicator. Refer
to Alan Hull's Active Investing course notes for more information.
Example
hullroad(-30,-20,12000000,10000000)
See Also
HullAtROAR | HullROAR

Hull ActVest ROAR


Usage
HULLROAR(ENTRY,CUTOFF,SLIQ,OLIQ)

entry

The ROAR must reach this level to start. Typically 30.

cutoff

If the ROAR falls below this level, it will drop back to zero.
Typically 20.

sLiq

Starting liquidity. The liquidity required to start the ROAR.


Typically 12M.

oLiq

Ongoing liquidity. The liquidity required to sustain the


ROAR. Typically 10M.
Description
HullROAR calculate Alan Hulls Active Investing Rate of Annual Return indicator. Refer
to Alan Hull's Active Investing course notes for more information.
Example
hullroar(30,20,12000000,10000000)
See Also
HullROAD | HullAtROAR

84
Function Reference

Inertia
Usage
INERTIA(N,SMOOTHING)

Number of periods.

smoothing

RVI periods.
Description
Calculates Donald Dorsey's Inertia indicator over n periods, using the given smoothing.

Intraday Momentum Index


Usage
IMI(N)

number of periods.
Description
Calculates the Intraday Momentum Index over n periods.
The Intraday Momentum Index (IMI) was developed by Tushar Chande. The calculation
of the IMI is very similar to the RSI (Relative Strength Index), except it uses the
relationship between the intraday opening and closing prices to determine whether the day
is 'up' or 'down.' If the close is above the open, it is an up day. If the close is below the
open it is a down day. Therein lies its tie to candlestick charting. For those familiar with
candlestick charting, the IMI separates the black and white candlesticks and performs a
RSI calculation on the candlestick bodies.
Example
imi(21)
See Also
Relative Strength Index

85
Getting Started with BullScript

Keltner
Usage
KELTNERTOP(N)
KELTNERBOT(N)

The number of periods used to calculate the bands.


Description
KeltnerTop and KeltnerBot calculate the top and bottom line respectively of the
Keltner Channel, for the given number of periods.
The Keltner Channel indicator is used to identify overbought / oversold conditions as well
as the trend strength of a market. When an asset's price is closer to the upper band than the
lower band, the market is considered overbought. Conversely, when an asset's price is
closer to the bottom band than the upper band, the market is considered oversold. An
advantage of Keltner Channel analysis compared to other indicators used to analyze trend
strength is that market lag is not as pronounced because Keltner Channels are extremely
sensitive to fluctuations in volatility.
Example
keltnertop(10)

Klinger Oscillator
Usage
KVO(N)

EMA signal periods.


Description
Calculates the Klinger Oscillator for the current bar. The Klinger Oscillator measures
trends of money flows based upon volume.

MACD
Usage
MACD()

86
Function Reference

Description
Calculates the MACD indicator. The MACD is approximately the difference between the
12 and 26 bar exponential moving averages. (The calculation of the moving averages is
slightly non-standard).
See Also
Price Oscillator

Market Facilitation Index


Usage
MARKETFACINDEX()

Description
Calculates the Market Facilitation Index according to the formula: (high -
low)/volume

Mass Index
Usage
MASS(N)

Number of periods.
Description
Calculates the Mass indicator over n periods.
The Mass index, described by Donald Dorsey, is developed to predict trend reversal by
comparing difference and range between high and low prices. If the Mass index is going
up, the range between high and low is bigger. If the Mass index is going down, the range
between high and low is smaller.
Example
mass(21)

Median Price
Usage
MP(N)

Description
Calculates the median price according to the formula: (high+low)/2. Importantly, this
is not the same as the Statistical Median.

87
Getting Started with BullScript

See Also
Midpoint | Statistical Median

MESA Adaptive Moving Average


Usage
MAMA()

Description
Calculates the MESA Adaptive Moving Average.

Midpoint
Usage
MID(EXPR[,N])

Description
Calculates the midpoint of the range of expr over the last n bars, or over the entire dataset
if n is not given.
Example
mid(CLOSE,21) will return the midpoint between the highest close and lowest close
over the last 21 periods.
mid(CLOSE) will return the midpoint of the close price over the entire dataset.
See Also
Median Price | Statistical Median

Minus Directional Movement (-DI)


Usage
MDI(N)

Number of periods.
Description
Calculates the Minus Directional Movement indicator over n periods.
Example
mdi(14)

88
Function Reference

See Also
+DI | DX | ADX | ADXR | CSI

Momentum
Usage
MO(EXPR[,N])

expr

Momentum will be calculated over this data. Eg: Close.

Number of periods.
Description
Calculates the Momentum indicator over n periods according to the formula:
(expr/hist(expr,n))*100
Example
mo(14)

Money Flow Index


Usage
MFI(N)

Number of periods.
Description
Calculates the Money Flow Index over n periods.
The money flow indicator compares upward changes and downward changes of the
volume weighted typical prices. This indicator is similar to the relative strength index,
with the difference being the volume weighted prices.
Example
mfi(14)
See Also
Relative Strength Index | Relative Volatility Index | Typical price

89
Getting Started with BullScript

Moving Average
Usage
MA(EXPR,N[,METHOD])

expr

The data that will be averaged. Eg: Close.

The length of the moving average, specified in bars


(ticks).

method

The type of the moving average (eg Simple). See the


table below.
Description
Calculates an n-period moving average of expr, using the given moving average method.
If method is not given, then a simple moving average will be calculated.
Example
ma(C,21,SIMPLE) will calculate a 21-period simple moving average of the close
price.
Moving Average Methods
Either the keywords or abbreviations listed below may be used as a method. You can also
get method as a parameter by using the InputMA function.

Keyword Abbreviation Description

Elastic Volume Weighted moving


ELASTICVOLUMEWEIGHTED ELASTIC
average.

ENDPOINT EP End Point moving average.

Exponential moving average. Strongest


weighting is given to the last day bars,
EXPONENTIAL E
and decaying in an exponential
fashion.

90
Function Reference

Simple moving average. Traditional


SIMPLE S moving average. Equal weighting is
assigned to each tick.

Time-Series moving average. A


TIMESERIES T moving average based on linear
regression.

Triangular moving average. Similar to


TRIANGULAR TRI running two identical simple moving
averages over each other.

WEIGHTED W Weighted moving average.

Wilder's moving average. A form of


exponential moving average used by
WILDERS WI
Wilder to make calculating by-hand
easier.

VARIABLE V Variable moving average.

VOLUMEADJUSTED VOL Volume-Adjusted moving average.

ZEROLAG ZERO Zero-Lag moving average.

See Also
InputMA | DEMA | TEMA

Negative Volume Index


Usage
NVI()

Description
Calculates the Negative Volume Index.
See Also
Positive Volume Index

On Balance Volume
Usage
OBV(EXPR)

91
Getting Started with BullScript

expr

The data that will be examined for increases and


decreases. Typically Close.
Description
Calculates the On Balance Volume indicator, using the specified data to determine
movement.
On Balance Volume was one of the first volume indicators to measure positive and
negative volume flows. Volume is added if expr moves up and subtracted if the expr price
moves down. The On Balance Volume indicator was developed by Joseph Granville.
Example
obv(C)

Parabolic SAR
Usage
SAR(STEP,MAXIMUM)

step

Rate of acceleration.

maximum

Maximum change per bar.


Description
Calculates Wilder's Parabolic Stop and Reverse indicator.
Example
sar(0.01,0.25)

Peak
Usage
PEAK(N,EXPR,CH)

The number of peaks ago.

expr

92
Function Reference

The data being processed.

ch

The % change required for the zig zag function.


Description
Returns the value of expr at n peaks ago, as determined by the Zig Zag function.
Example
peak(1,H,8) returns the value of High at the last peak on a 8% ZigZag on High.
See Also
PeakBars | Trough | TroughBars | ZigZag

PeakBars
Usage
PEAKBARS(N,EXPR,CH)

The number of peaks ago.

expr

The data being processed.

ch

The % change required for the zig zag function.


Description
Returns the number of bars since the nth peak ago occured for expr, as determined by the
Zig Zag function.
Example
peakbars(1,H,8) returns the number of bars since the last peak on a 8% ZigZag on
High.
See Also
Peak | Trough | TroughBars | ZigZag

93
Getting Started with BullScript

Performance
Usage
PER(EXPR)

expr

Performance will be calculated on this data.


Description
Calculates the performance of expr since the beginning of the dataset. The performance is
the percentage that expr has changed since the beginning of the dataset.
Example
per(Close)

Plus Directional Movement (+DI)


Usage
PDI(N)

Number of periods.
Description
Calculates the Plus Directional Movement indicator over n periods.
Example
pdi(14)
See Also
-DI | DX | ADX | ADXR | CSI

Positive Volume Index


Usage
PVI()

Description
Calculates the Positive Volume Indicator.
See Also
Negative Volume Index

94
Function Reference

Price Channel
Usage
PRICECHANNELHIGH(N)
PRICECHANNELLOW(N)

Number of bars used in calculation.


Description
PRICECHANNELHIGH and PRICECHANNELLOW calculate the top and bottom line of an
n-period Price Channel indicator respectively. That is, the highest high and lowest low of
the trailing n bars.
Example
pricechannelhigh(21)
pricechannellow(21)

Price Oscillator
Usage
OSCP(N1,N2,METHOD,DIFFTYPE)

n1

Length of first moving average used in calculation.

n2

Length of first moving average used in calculation.

method

Type of moving average, such as exponential.

difftype

Points or percent.
Description
The Price Oscillator calculates difference between two moving averages of length n1 and
n2, calculated using the method moving average method. The result is either given as a
percent or as a value, depending on the value of difftype used.

95
Getting Started with BullScript

Example
oscp(14,21,SIMPLE,POINTS)
See Also
InputROC | MACD | Volume Oscillator

Price Volume Trend


Usage
PVT()

Description
Calculates the Price & Volume Trend indicator, which is the cumulative volume total,
calculated using relative changes of the close price.

Projection Band
Usage
PROJBANDTOP(N)
PROJBANDBOT(N)

Number of periods used in calculation.


Description
PROJBANDTOP and PROJBANDBOT calculates the top and bottom of the n-period
projection band respectively.
Projection Bands are calculated by finding the minimum and maximum prices over the
specified number of days and projecting these forward. The results consists of two bands
representing the minimum and maximum price boundaries. Prices will always be
contained by the bands, unlike Bollinger Bands.
Example
projbandtop(21)
projbandbot(21)
See Also
Projection Oscillator

Projection Oscillator
Usage
PROJOSC(N,SMOOTHING)

96
Function Reference

Number of periods used in initial calculation.

smoothing

Number of days used in smoothing average.


Description
Calculates the Projection Oscillator for n periods, with the specified smoothing. The
Projection Oscillator shows where the current price is relative to the Projection bands.
See Also
Projection Bands

Qstick
Usage
QSTICK(N,METHOD)

Number of periods used in calculation.

method

Moving average method


Description
Calculates the Q-Stick indicator. Developed by Tushar Chande as a way to quantify
candlesticks, the QStick indicator is a moving average of the difference between the
opening and closing prices of an issue.
The formula used to calculate Q-Stick is: ma(close-open,n,method)
Example
qstick(21)

Rally
Usage
RALLY()

97
Getting Started with BullScript

Description
Returns 1 when the current bar rallies from the previous one, and a 0 otherwise. A bar
rallies when its high price is greater than the previous bar's high price, and its low price is
greater than or equal to the previous bar's low price.

Rally with Volume


Usage
RALLYWITHVOL()

Description
Returns 1 when the current bar rallies with volume from the previous one, and a 0
otherwise. A bar rallies with volume if it rallies, and its volume is higher than for the
previous bar.

Random Walk Index


Usage
RWI()

Description
Michael Poulos developed the Random Walk Index in an effort to find an indicator that
overcomes the effects of a fixed look-back period and the drawbacks of traditional
smoothing methods.
The Random Walk Index is based on the basic geometric concept that the shortest distance
between two points is a straight line. The further prices stray from a straight line during a
move between two points in time, the less efficient the movement.

Range Indicator
Usage
RANGEINDICATOR(N,SMOOTHING)

Description
Calculates the Range Indicator, developed by Jack Weinberg, over n periods, with the
specified smoothing.
Example
rangeindicator(21,4)

Rate of Change
Usage
ROC(EXPR,N,DIFFMETHOD)

98
Function Reference

expr

Input data used in calculation.

Number of periods used in calculation.

diffmethod

Either points or percent.


Description
Calculates the rate of change of expr at the current bar to what it was n bars ago.
Diffmethod may be percent, in which case the difference will be a percentage, or
points in which case the difference will be the number of points moved.
Example
roc(CLOSE,14,POINTS)
See Also
InputROC

Reaction
Usage
REACTION()

Description
Returns 1 when the current bar is in reaction from the previous one, and a 0 otherwise. A
bar is in reaction when its high price is less than or equal to the previous bar’s high price,
and its low price is less than the previous bar’s low price.

Reaction with Volume


Usage
REACTIONWITHVOL()

Description
Returns 1 when the current bar is in reaction with volume from the previous one, and a 0
otherwise. A bar is in reaction with volume when it is in reaction, and the current bar’s
volume is greater than the previous bar’s volume.

99
Getting Started with BullScript

Relative Strength Index


Usage
RSI(N)

Number of periods used in calculation.


Description
Calculates the Relative Strength Index for n periods.
The Relative Strength index was developed by J. Welles Wilder. It is a momentum
oscillator that compares upward movements of the close price with downward
movements, resulting in a value which ranges between 0 and 100.
Example
rsi(21)
See Also
Money Flow Index | Relative Volatility Index

Relative Volatility Index


Usage
RVI(N)

Number of periods used in calculation.


Description
Calculates the Relative Volatility Index for n periods. The RVI measures the direction of
volatility on a scale from zero to 100.
Developed by Donald Dorsey, the Relative Volatility Index is the Relative Strength Index
only with the standard deviation over the past 10 days used in place of daily price change.
Use the RVI as a confirming indicator as it makes use of a measurement other than price
as a means to interpret market strength.
Example
rvi(21)
See Also
Money Flow Index | Relative Strength Index

100
Function Reference

R-Squared Indicator
Usage
RSQUARED(EXPR,N)

expr

Input data used in calculation.

Number of bars used in calculation.


Description
Calculated the R-Squared indicator over expr.
Example
rsquared(CLOSE,14)

Stochastic Momentum
Usage
STOCHMOMENTUM(KPERIODS,SMOOTHING,DOUBLESMOOTHING,DPERIODS,METHOD)

kperiods

%K Time periods

smoothing

%K Smoothing period

doublesmoothing

%K Double smoothing

dperiods

%D Time periods

method

%D Moving Average Method

101
Getting Started with BullScript

Description
Calculates the Stochastic Momentum for expr using the given settings.
The Stochastic Oscillator provides you with a value showing the distance the current close
is relative to the recent n-period high/low range, the SMI shows you where the C is
relative to the midpoint of the recent n-period high/low range. The result is an oscillator
that ranges between +/- 100 and is a bit less erratic than an equal period Stochastic
Oscillator.
Example
stochmomentum(5,3,3,3,SIMPLE)
See Also
Stochastic Oscillator

Stochastic Oscillator
Usage
STOCH(N,SLOWING)

Number of periods used in the main calculation.

slowing

Number of periods used in the 'slowing' smoothing


average.
Description
Calculates the Stochastic Oscillator over n periods, using the given number of periods
slowing.
Example
stoch(8,5)
See Also
Stochastic Momentum

Swing Index
Usage
SWING(LIMIT)

limit

102
Function Reference

Limit of movement.
Description
Calculates the Swing Index indicator with the given limit of movement.
This indicator assigns a Swing Index value from 0 to 100 for an up bar and 0 to -100 for a
down bar. This indicator uses the current bar's open, high,low and close as well as the
previous bar's open and close to calculate the Swing Index values.
Example
swing(7.5)
See Also
Accumulated Swing Index

TEMA
Usage
TEMA(EXPR,N)

expr

Input data used in calculation.

Number of periods used in calculation.


Description
Calculates the TEMA indicator for expr over the last n periods. TEMA is a composite of a
single, double, and triple exponential moving average.
Example
tema(close,14)
See Also
Moving Averages

Time Series Forecast


Usage
TSF(EXPR,N)

expr

103
Getting Started with BullScript

Input data used in calculation.

Number of periods used in calculation.


Description
Calculates the n-period time series forecast of expr.
Example
tsf(close,14)

TRIX
Usage
TRIX(N)

Number of periods used in calculation.


Description
Calculates the n-period TRIX indicator.
Example
trix(14)

Trough
Usage
TROUGH(N,EXPR,CH)

The number of troughs ago.

expr

The data being processed.

ch

The % change required for the zig zag function.

104
Function Reference

Description
Returns the value of expr at n troughs ago, as determined by the Zig Zag function.
Example
trough(1,L,8) returns the value of Low at the last trough on a 8% ZigZag on Low.
See Also
Peak | PeakBars | TroughBars | ZigZag

TroughBars
Usage
TROUGHBARS(N,EXPR,CH)

The number of troughs ago.

expr

The data being processed.

ch

The % change required for the zig zag function.


Description
Returns the number of bars since the nth trough ago occured for expr, as determined by
the Zig Zag function.
Example
troughbars(1,L,8) returns the number of bars since the last trough on a 8% ZigZag
on Low.
See Also
Peak | PeakBars | Trough | ZigZag

Typical Price
Usage
TYPICAL()

105
Getting Started with BullScript

Number of periods used in calculation.


Description
Calculates the typical price, according to the formula: (High + Low + Close)/3

Ultimate Oscillator
Usage
ULTIMATE(N1,N2,N3)

n1

First cycle length.

n2

Second cycle length.

n3

Third cycle length.


Description
Calculates the Ultimate Oscillator, using n1, n2, and n3 as cycle lengths.
The ultimate oscillator calculates the sums of the True Ranges of the number of bars
specified by the inputs n1, n2, and n3. These sums are divided into the sums of the
distance from the close to the low. This value is weighted for the three lengths to give the
final result.

Variance
Usage
VAR(EXPR,N)

expr

Data to evaluate.

Number of bars.

106
Function Reference

Description
Calculates the statistical variance of expr over the last n bars.
Example
var(CLOSE,14)

Vertical Horizontal Filter


Usage
VHF()

Description
Calculates the Vertical Horizontal Filter indicator.

Volatility
Usage
VOL([MAPERIODS,ROCPERIODS])

maperiods

Moving average periods.

rocperiods

Rate of change periods.


Description
Calculates Chaikin’s Volatility indicator, using the given number of moving average
periods, and the given number of periods for the rate of change. Maperiods and
rocperiods are each set to 10 if they are not given.
The Volatility Chaikins indicator measures the difference between high and low prices.
This formula is used to indicate the top or bottom of the market. This formula was
developed by Marc Chaikin.
Example
vol(15,20)

Volume Oscillator
Usage
OSCV(N1,N2,METHOD,DIFFTYPE)

n1

107
Getting Started with BullScript

Length of first moving average used in calculation.

n2

Length of first moving average used in calculation.

method

Type of moving average, such as exponential.

difftype

Points or percent.
Description
Calculates the volume oscillator, using n1 and n2 length moving averages, calculated
using the method moving average method, with the given difference calculation type used.
Example
oscv(14,21,SIMPLE,POINTS)
See Also
InputROC | Price Oscillator

Weighted Close
Usage
WC()

Description
Calculated the Weighted Close indicator according to the formula: (close*2 + high
+ low)/4

Wilder's Smoothing
Usage
WILDERS(EXPR,N)

expr

Data to be smoothed.

108
Function Reference

Smoothing periods.
Description
Smooths expr using Wilder's Smoothing indicator over n periods.
Example
wilders(CLOSE,14)

Williams' %R
Usage
WILLR(N)

Number of periods.
Description
Calculates Williams’ %R indicator over n periods.
Example
willr(14)

Williams' A/D
Usage
WILLA

Description
Calculates Williams’ A/D indicator.

ZigZag
Usage
ZIGZAG(EXPR,CH,METHOD)

expr

The data being processed. Eg: Close.

ch

Minimum reversal amount.

109
Getting Started with BullScript

method

Reversal method. Points or Percent.


Description
Calculates the ZigZag indicator for the data given in expr.
Example
zigzag(C,10,%)
See Also
InputRoc
Peak
PeakBars
Trough
TroughBars

110
Attribute reference
Attribute Reference
The following pages list the attributes that are built into BullScript. Attributes are used to
provide additional information about how your BullScript should be applied.

Attributes
Using Attributes
BullScript allow you to specify the way you want the results of a script to be displayed
within the script itself, using its attributes system.
Attributes are defined within square brackets, ‘[‘ and ‘]’, and appear before the plots that
they relate to. They consist of the name of the attribute being used, followed by an ‘=’,
followed by the value of the attribute.
For instance, if you wanted to plot a 28-day simple moving average and a 14- day simple
moving average, but you wanted the 28-day moving average to be displayed in green, and
the 14-day moving average to be displayed in red, you could use the following code:
[color=green]
ma(C,28,SIMPLE);
[color=red]
ma(C,14,SIMPLE);
If a plot has more than one attribute, the attributes may be seperated by semicolons, or
placed in separate sets of square brackets. For example, if you wanted to plot a 14-day
moving average in red, on a new pane, you could use,
[color=red; target=price]
ma(C,14,SIMPLE);
or
[color=red]
[target=price]
ma(C,14,SIMPLE);
Some attributes, such as author and category may take multiple values. All values must be
given in the same attribute, and must be separated by pipes. See the table below for
details.
[category=Moving Average|Verticality]
ma(C,14,SIMPLE);

111
Getting Started with BullScript

Available Attributes
Possible
Attribute Description Examples
Values

An alternative
name by
which the
formula may
be called
Alias Any text [alias=MyRSI]
within
BullScript.
This will often
be an
abbreviation.

The author of
the indicator.
By
convention,
use the last
Any text (for [category=Hull, Alan]
name then the
Author example Hull, [category=Guppy,
first name. Daryl|Wilson, Leon]
Alan)
Multiple
authors may
be listed,
separated by
pipes.

The category
that the
formula is in.
Any text (for Multiple [category=Moving Average]
Category
example Volume) categories may [category=Volume|My Own]
be listed,
separated by
pipes.

A reference to
Citation Any text documentation [citation="Trading Systems,
on which the Wilder"]
formula is

112
Attribute reference

based.

Colour names or
The default
RGB values given [color=red]
Color colour of the
as [color=rgb(0,255,128)]
plot.
rgb(red,green,blue)

A description
of the formula.
[description="The moving
This will
Description Any text average can be used to
appear on the
smooth noisy data"]
Insert
Indicator page.

Background
Name of pattern to
FillStyle pattern for [fillstyle=Weave]
use. See list.
ribbons.

Default, or any The font face,


font name, eg: or family, used [font="Courier New"]
Font
Verdana, Arial, for markers [font=Default]
Wingdings and text plots.

The size of the


Default, or a font in points [fontsize=12]
FontSize
positive number. for markers [fontsize=Default]
and text plots.

Default, or any of
The style of
Bold, Underline,
the font for [fontstyle=Bold,Underline]
FontStyle Italic or Strikeout
markers and [fontstyle=Default]
separated by
text plots.
commas.

Levels at
List of numbers which
HorzLine separated by horizontal [horzline=20,80]
commas. lines should be
displayed.

Solid, Dotted,
LineStyle The style with [linestyle=step]
Dash, Long Dash,
which the plot
Step, Dotted Step,

113
Getting Started with BullScript

Horz Step, Bar, will be drawn.


Grounded Bar,
Points, Marker,
Fill, NoPlot, Text.

If an indicator
has this
attribute and it
is included in a
scan, then
LinkedChart SelectionOnly when a linked [linkedchart=selectiononly]
chart is
created, only
selected plots
are shown on
the chart.

The name for


Name Any text an individual [name=Signal Line]
plot.

The password
must be
entered to
view or edit
Password Text [password=12345]
the indicator
script again -
but not to use
the indicator.

The timeframe
that this
indicator
Daily, Weekly, intended for
Period Monthly, use on. Do not [period=Weekly]
Quarterly, Yearly specify if the
indicator can
be used on any
timeframe.

Normally an
SortPlots ByName indicators [sortplots=byname]
plots are

114
Attribute reference

shown in the
properties
window in the
order they are
scripted. This
attribute
causes them to
be sorted by
name.

Price, Volume, The pane and


New Pane, New scale that the
Target [target=price]
Axis, Overlay, plot will use
Percent, Default by default.

Specifies
[TextAlign=Above, Left]
Center, Above, where text is
TextAlign [TextAlign=Right, Center]
Below, Left, Right placed relative [TextAlign=Below]
to a data point.

Allows
advanced
formatting
[TextFormat=00 00 00 00]
Default, other options for
TextFormat [TextFormat=E]
format string displaying [TextFormat=default]
dates and
numbers as
text.

Specifies the
transparency
for a filled
linestyle. 0 for
Number between 0
Transparency completely [transparency=95]
and 100
opaque and
100 for
completely
transparent.

Whether or not
the plot is
Visible Yes, No [visible=no]
visible by
default.

115
Getting Started with BullScript

The width of
Width Positive number [width=2]
the plot line.

Color Attribute
Usage
[color=named-color]
[color=rgb(red,green,blue)]

named-color

See the list below.

red

The red component of a colour. An integer between 0 and


255 inclusive.

green

The red component of a colour. An integer between 0 and


255 inclusive.

blue

The red component of a colour. An integer between 0 and


255 inclusive.

Description
Specifies the color for the following plot or ribbon component. You can either specify one
of the named-colors listed below, or you can specify a colour exactly using the RGB
notation.
Colour names are case insensitive and space insensitive. That is, you can remove the
spaces from colour names and they will work as expected.

Example
[color=Red]
[color=AliceBlue]
[color=aliceblue]

116
Attribute reference

[color="Alice Blue"]
[color=rgb(0,128,255)]

Named Colors
• Alice • Dark • Light Sea •
Blue Turquoise Green Papaya
• Antique • Dark Violet • Light Sky Whip
White • Deep Pink Blue •
• Aqua • Deep Sky • Light Peach
• Blue Slate Gray Puff
Aquamarin • Dim Gray • Light • Peru
e • Dodger Blue Steel Blue • Pink
• Azure • Firebrick • Light • Plum
• Beige • Floral White Yellow •
• Bisque • Forest Green • Lime Powder
• Black • Fuchsia • Lime Blue
• • Gainsboro Green •
Blanched • Ghost White • Linen Purple
Almond • Gold • Magenta • Red
• Blue • Goldenrod • Maroon • Rosy
• Blue • Gray • Medium Brown
Violet • Green Aquamarine •
• Brown • Green • Medium Royal
• Burly Yellow Blue Blue
Wood • Honeydew • Medium •
• Cadet • Hot Pink Orchid Saddle
Blue • Indian Red • Medium Brown
• • Indigo Purple •
Chartreuse • Ivory • Medium Salmon
• • Khaki Sea Green •
Chocolate • Lavender • Medium Sandy
• Coral • Slate Blue Brown
• Cornsilk LavenderBlush • Medium • Sea
• Crimson • Lawn Green Spring Green Green
• Cyan • Lemon • Medium • Sea
• Dark Chiffon Turquoise Shell
Blue • Light Blue • Medium •
• Dark • Light Coral Violet Red Sienna
Cyan • Light Cyan • Midnight •
• Dark Blue Silver
• Light
Goldenrod Goldenrod • Mint • Sky

117
Getting Started with BullScript

• Dark Yellow Cream Blue


Gray • Light Gray • Misty • Slate
• Dark • Light Green Rose Blue
Green • Light Pink • Moccasin • Slate
• Dark • Light • Navajo Gray
Khaki Salmon White • Snow
• Dark • Navy •
Magenta • Old Lace Spring
• Dark • Olive Green
Olive • Olive • Steel
Green Drab Blue
• Dark • Orange • Tan
Orange • Orange • Teal
• Dark Red •
Orchid • Orchid Thistle
• Dark • Pale •
Red Goldenrod Tomato
• Dark • Pale •
Salmon Green Turquoi
• Dark • Pale se
Sea Green Turquoise •
• Dark • Pale Violet
Slate Blue Violet Red •
• Dark Wheat
Slate Gray •
White

White
Smoke

Yellow

Yellow
Green

See Also
Attributes

118
Attribute reference

FillStyle Attribute
Usage
[fillstyle=style-name]

style-name

See the list below.

Description
Specifies the fill style to be used on the ribbon backgound.

Example
[fillstyle=SmallConfetti]

Fill Style Names

• Backward Diagonal • Percent 05

• Dark Downward Diagonal • Percent 10

• Dark Horizontal • Percent 20

• Dark Upward Diagonal • Percent 25

• Dark Vertical • Percent 30

• Dashed Downward Diagonal • Percent 40

• Dashed Horizontal • Percent 50

• Dashed Upward Diagonal • Percent 60

• Dashed Vertical • Percent 70

• Diagonal Brick • Percent 75

• Diagonal Cross • Percent 80

• Divot • Percent 90

• Dotted Diamond • Plaid

119
Getting Started with BullScript

• Dotted Grid • Shingle

• Forward Diagonal • Small Checker Board

• Horizontal • Small Confetti

• Horizontal Brick • Small Grid


• Solid
• Large Checker Board
• Solid Diamond
• Large Confetti
• Sphere
• Large Grid
• Trellis
• Light Downward Diagonal
• Vertical
• Light Horizontal
• Wave
• Light Upward Diagonal
• Weave
• Light Vertical
• Wide Downward Diagonal
• Narrow Horizontal
• Wide Upward Diagonal
• Narrow Vertical
• Zig Zag
• Outlined Diamond

See Also
Attributes

LineStyle Attribute
Usage
[linestyle=style-name]

style-name

See the list below.

120
Attribute reference

Description
The linestyle attribute describes how the following calculations will be display. Most of
the possible line styles change the formatting of a normal plot line.
There are several special formats available, some of which apply to results in pairs. See
below for a detailed example of using various linestyles.

Normal LineStyle values


Value Description Examples

Solid,
Dotted, Draws diagonal lines in the style [linestyle=Solid]
Dash, Long described from points to point. ma(C,10,S);
Dash

Draws stepped lines in the style


Step, described from point to point. A
Dotted horizontal line is drawn right from the [linestyle=Step]
Step, Horz previous point to the location of the next (H+L)/2;
Step point, then a vertical line is drawn to the
second point.

Vertical bars are drawn from zero to the


[linestyle=Bar]
Bar current point. Suitable for bar charts that
macd-ma(macd,9,e);
may go negative.

Vertical bars are drawn from the bottom


[linestyle=Grounded
Grounded of the chart pane to the current point.
Bar]
Bar Suitable for bar charts that will always be close*volume;
positive, such as volume.

[linestyle=Points]
Points Dots are drawn at each value.
sar();

Special LineStyle values


Value Description Inputs Examples

The expression is [linestyle=marker]


Marker interpreted as true/false. If 1 [marker=Long]
'true' is returned then a cross(C,ma(C,10));

121
Getting Started with BullScript

signal marker is drawn.


Used in conjunction with
the marker attribute, which
specifies which marker to
draw. Markers can also be
used as a scan criteria in
BullScan. Note: The show
markers indicator option
must be checked for
markers to appear on a
chart.

Behaves the same as


marker, except a vertical [linestyle=verticalmarker]
VerticalMarker line that extends through 1 [marker=Long]
the chart gets shown cross(C,ma(C,10));
instead of an icon.

This result never gets


drawn on a chart. This is
useful for making a
[linestyle=hidden]
NoPlot calculation available to 1
DarvasBoxNumber();
BullScan without having
them appear on a chart. See
also: visible attribute.

Expressions are accepted


in pairs. The first
expression determines the
text to show, and the
second determines where it [linestyle=text]
Text is shown (in terms of the y- 2 "Price is "+C;
axis). If either expression HIGH;
returns undefined then no
text is shown. Various
attributes are available for
formatting text.

Expressions are accepted [linestyle=fill]


in pairs, and the gap [color=Green]
Fill, Fill
between the two 2 macd();
Step
expressions is filled. With [color=Red]
fill, the two expressions ma(macd(),9,e);

122
Attribute reference

describe an area using


normal (diagonal) lines,
whereas Fill Step describes
an area using stepped lines.
The colour attribute can be
used ahead of each of the
two expressions, and the
colour of the expression on
top is used as the fill
colour.

Expressions are accepted


in pairs. Vertical bars are
drawn between the two
expression points. The
[linestyle=fill bars]
same colouring rules apply
Fill Bars 2 hhv(high,30);
as for Fill. Fill Bars can be llv(low,30);
used in conjunction with
Fill Step and Horz Step to
construct boxes such as the
Darvas boxes.

Four expressions should


follow this attribute. They
will be evaluated and
treated as the open, high,
low and close values of a
candlestick respectively.
[linestyle=candle]
Note that this will not
open;
effect the price values as
Candle 4 max(H,hist(C,1));
seen by other scripts, or min(L,hist(C,1));
pattern tools - it is simply a close;
method of formatting the
four expressions. If an
indicator has target=Price
and a candle plot then it
will prompt you to hide the
real price plot.

[linestyle=signal]
Equivalent to
Signal 1 [marker=Long]
[linestyle=marker].
cross(C,ma(C,10));

123
Getting Started with BullScript

Allows an indicator to
dynamically select the
colour for the price plot.
Works in a similar way as
the ribbon. Ie, specify
[linestyle=pricecolor]
several expressions, and
PriceColor many [color=Red] C<hist(C,1);
the colour of the first one
[color=Green] C>hist(C,1);
to evaluate to true gets
used for the current bar.
See the JB Volatility Profit
Taker indicator for an
example of this feature.

Example 1 - Fills and Markers


This chart can be created using the script shown below. It is a modified version of the
built-in "Moving Average - Crossover" indicator. The script demonstrates the Dash, Fill
and Marker line styles.

[target=Price]
[name=Short MA]
shortMA := ma(Close,5,simple);
shortMA;
[name=Long MA; linestyle=Dash]
longMA := ma(Close,13,simple);
longMA;

124
Attribute reference

{ Fill }
{ Note that fill is green when shortMA is above longMA. }
[linestyle=Fill]
[color=shortMA] res1;
[color=longMA] res2;

{ Markers }
{ The name attribute automatically gets shown as a label. }
{ Use 'tooltip' to display a message when you hover over the
marker. }
[name=Above; linestyle=marker; marker=Long]
[tooltip="Short MA passed above Long MA"]
cross(shortMA,longMA);

[name=Below; linestyle=marker; marker=Short]


[tooltip="Short MA passed below Long MA"]
cross(longMA,shortMA);

Example 2 - Generating Text


Text can be generated and placed on the chart. The script below generates text for peaks
and troughs of the zigzag function. Note that each text element is followed by two
expressions. The first one determines the text to be shown, or undefined if no text is to be
shown, and the second one indicates at what price level the text should be drawn.
Combining the price level with the textalign attribute, the 'peak' label is drawn Above the
High price.

125
Getting Started with BullScript

[target=Price]
size := input("Zig zag size",4,0);
z := zigzag(Close,size,%);
ispeak := z>hist(z,1) and z>future(z,1);
istrough := z<hist(z,1) and z<future(z,1);

[linestyle=Solid; color=Red]
z;

[color=Blue]
[linestyle=Text; textalign=Above,Center]
if(isPeak, "Peak at " + z, undefined);
High;

[linestyle=Text; textalign=Below,Center]
if(isTrough, "Trough at " + z, undefined);
Low;

See Also
Attributes

126
Attribute reference

Target Attribute
Usage
[target=target-type]

target-type

See the list below.

Description
Specifies the pane and/or axis that the indicator should appear on by default. Note that this
can be overridden when the indicator is inserted.
BullCharts also has an option in the preferences to control how any indicator marked as
target=default should be treated. It is recommended that newaxis, newpane and overlay
not be used in light of this preference.
Presently only one target can be applied per script, however this may be revised in future
versions of BullCharts.

Example
[target=Price]
ma(C,10,S) * 1.1;
ma(C,10,S) * 0.9;

Accepted Target Types


Name Description

No special treatment should be applied to this indicator. By default a new


default pane will be created, however this can be changed in the application
preferences. Using target=default is equivalent to if no target is specified.

The indicator is added to the current (last clicked) pane and a new axis is
newaxis
created on the left hand side, replacing any axis that was previously there.

The indicator will be placed in a new pane, regardless of the whether the
newpane application preferences say that indicators should be placed. It is generally
better to use default.

overlay The indicator is added to the current (last clicked) pane. An axis is only

127
Getting Started with BullScript

shown if either side doesn't have one already.

Indicates that the resuls generated are of a percentage nature. Presently this is
percent
treated the same as default.

Indicator should appear on the same pane and axis as the selected price plot.
This is recommended for indicators that function similar to moving averages.
price
The results should be in roughly the same range as those for the price chart or
scaling problems may result.

The indicator should be displayed as a ribbon (a thick coloured bar at the


ribbon bottom of the chart). One true/false result should be be returned for each
ribbon mode. See the Ribbon help topic for more details.

Indicator should appear on the same pane and axis as the volume plot. If the
volume volume pane is not currently visible then it will be shown. The indicator
should give results roughly in the same range as the volume data.

See Also
Attributes | LineStyle | Ribbons

128
Best Practices
As with many programming languages, BullScript can be used well or poorly. When
writing your own scripts, we advise that you endeavor to write them in a clean, clear
fashion for several reasons:

1. Your scripts will be easier to understand by others.


2. You will be more able to spot potential problems, or bugs, in your script.
3. It will be easier for you to modify your script at a later date.
4. If you intend on publishing your scripts, they will appear more professional.

Here are several guidelines that we suggest you follow when writing scripts:

• Use descriptive names when naming your scripts and their inputs. For example,
use "Smoothing periods" instead of "smooth" as an input.
• Add inputs to your script, so that results can be easily customized without having
to edit the script. Give a sensible default value for each input.
• Specify maximum and minimum allowed values for inputs as appropriate. For
example, an input that will be used to adjust the length of a moving average
should have a minimum value of at least 1. Don’t specify a maximum value
unnecessarily.
• Use consistent capitalisation when entering function names and variable names.
This will make your script more readable.
• White space (spaces and new lines) can be used to make your program more
readable. Use white space consistently. For example, put a space before and after
operators (+, -, *, /, :=, etc...).
• For complicated scripts, group sections of your script together that logically
belong together. For example, list all of your inputs together at the top. Then do
all of your calculations together. Finally return all of the results together.
• Only assign one variable per line. For example: a:=O+H; b:=a*3;
c:=b+D; should not all be given on a single line.
• Remember to use attributes to add meaning to your script. For example, if an
indicator logically belongs with the price, such as ma(typical(),5), then
use the [target=Price] attribute.
• When multiple results are being returned, use the name attribute to give each
result a meaningful name. For example: "MACD" and "Signal".
• If you publish your script, use the citation attribute so other people will
remember where they found the script. Include a web address if appropriate.

129
Getting Started with BullScript

• Use comments to describe any unusual steps in your script. However, a general
description of your indicator should be put in a description attribute. Use proper
grammar and punctuation for both comments and descriptions.
• Assign intermediate results to variables, rather than including them inline. This is
particularly important for complicated scripts. For example:
tmp := (O+H+L+C)/4;
ma(tmp,5,S) + ma(tmp,7,S);
is better than: ma((O+H+L+C)/4,5,S) + ma((O+H+L+C)/4,7,S);
• Use the BullScript functions to simplify your scripts where ever possible. For
example: use ma(C,n,S) instead of sum(C,n)/n when calculating a moving
average. Or use typical instead of (H+L+C)/3.
• Carefully test your scripts to ensure that they are working as expected. For
example, you may accidentally enter sum(C,m) when you intended
sum(C,n), but the mistake will only be revealed with testing if both m and n
are in use.
• Surround text attributes with quotes. [name="Modified Moving
Average"] rather than [name=Modified Moving Average] to make it
clear when the value begins and ends.

130
Sample Scripts
This section contains a number of popular indicators written in BullScript. All these
indicators are provided by BullScript, but sample formulae are provided here to
demonstrate how BullScript may be used to construct indicators.
The examples below have been coloured in the same way that the BullScript syntax
highlighter would colour them.

Exponential Moving Average


An 18% exponential moving average could be constructed in BullScript using the
formula:
percent := 0.18;
C*(1-percent) + previous*percent

Gap Up
A gap up occurs when the low price of the current candlestick is higher than the high price
of the previous candlestick.
low > hist(high,1)

Simple Moving Average


A 14-period simple moving average could be calculated by dividing the sum of close
prices for the last 14 periods by 14.
sum(C,14)/14

Typical Price
The typical price is the average of the high, low and close.
(H+L+C)/3

Weighted Close
(high+low+close*2)/4

See Also
Sample Indicator

131
Sample Indicator
This topic is designed to help you create advanced indicators by examining one of the
indicators that comes built into BullScript: the Stochastic Oscillator. First a simple
Stochastic formula script is shown, then a more advanced version, as used in BullCharts,
is shown, then a discussion of script follows.
Note: You can access the scripts for all of the indicators in BullCharts

A Simple Stochastic Oscillator Script


The following formula could be used for Stochastic Oscillator. BullScript will let you
enter this directly as a script and it will work ok.
(sum(C-llv(L,5),3) / sum(hhv(H,5)-llv(L,5),3)) * 100;
However, by adding some extra attributes and inputs we can make the script much more
useful.

The BullCharts Stochastic Oscillator Script


Note: The line numbers here are not part of BullScript, but are added to assist discussion
of the script.
Colouring has been added in the same way that the BullScript syntax highligher would
colour a script.

01 [description="When a trend is upward, there is a


tendency that close price will be very close to that
02 day's high. During a downward trending market there is a
tendency that close price is close to low price.
03 The Stochastic Indicator helps to find trend reversal
searching for a period when close prices is close to
04 low price in up trending market or close prices is close
to high price in down trending market.
05 This formula has two output values: %K - Simple
Stochastic Indicator and %D - Smoothed Stochastic
06 Indicator (Moving Average of %K)."]
07 [citation="''Lane's Stochastics'' by George C. Lane,
M.D.Stocks & Commodities March 1994 www.traders.com"]

133
Getting Started with BullScript

08 [target=Percent; category=Oscillators; alias=stoch]


09
10 [horzlines=80,20]
11
12 kperiods := input("%K Time periods",5,1);
13 kslowing := input("%K Slowing periods",3,1);
14 dperiods := input("%D Time periods",3,1);
15 method := inputma("%D Method",S);
16 expr := expression("Expression");
17 signalperiods := input("Buy/Sell signal periods",200,1);
18
19 [name=%K]
20 kay := (sum(C - llv(L,kperiods),kslowing) /
sum(hhv(H,kperiods) - llv(L,kperiods),kslowing)) * 100;
21 kay;
22
23 [name=%D; linestyle=Dash]
24 ma(kay,dperiods,method);
25
26 { Markers }
27 [name=Above 20; linestyle=marker; marker=type1;
tooltip="Stochastic rose above 20"]
28 cross(kay,20) and expr > ma(expr,signalperiods,method);
29
30 [name=Below 80; linestyle=marker; marker=type2;
tooltip="Stochastic fell below 80"]
31 cross(80,kay) and expr < ma(expr,signalperiods,method);

Description and Citation


A description attribute is a good way to indicate to users of your BullScript how to
interpret the script, or what the script is designed to do. This information is shown in

134
Sample Indicator

BullCharts on the Insert Indicator dialog. Note that the description tag spans multiple
lines. BullCharts will wrap the text of any back into a single line.
If you are not the original designer of an indicator, then a citation will both give credit to
the original author, as well as direct users to further information on the script in question.
Or if you have designed the indicator yourself, it is a good way to link the script back to
your own website or books. The citation will appear in BullCharts below the description.
It is a good practice to enclose description, citation, and any textual attributes in a pair of
quotes.

Target Attribute
Line 8 of the script appears as follows:
[target=Percent; category=Oscillators; alias=stoch]
Any number of attributes can be placed on a single line by separating them with a
semicolon (;). This can keep the script tidy. Note: If you want to use a semicolon in a
description, the text must be enclosed in quote marks.
The target attribute tells BullCharts the type of data that will be generated. This
information allows BullCharts to make intelligent choices about scaling, etc. For example,
an indicator with [target=price] will automatically appear on the same scale as the
price. See attributes for more details.

Category Attribute
By specifying a category, this indicator can be more easily found in the Insert Indicator
dialog by using the drop down category list. It is recommended that you use the existing
categories if applicable - but you may also create a new category simply by picking a
unique name. For example, if you have designed and published several indicators you
may want to use your name as a category - so users of your indicators can group them
easily.
An indicator can be listed under multiple categories by separating them with a comma.

Alias Attribute
You may want to refer to this indicator from another indicator. If the indicator name
contains spaces (such as "Stochastic Oscillator") then normally you can't directly refer to
the indicator in code - the formula function would be required instead.
The alias attribute allows you to specify a short name to be used in other scripts,
without sacrificing having a descriptive name for your indicator. In this case,
alias=stoch means that these two lines are equivalent in another script:

135
Getting Started with BullScript

formula("Stochastic Oscillator")
stoch()

Horzlines
The horzlines attribute, on line 10, allows any number of horizontal lines to be added
to the indicator. In BullCharts these can be subsequently modified or hidden by using the
indicator properties dialog. Here 80% and 20% are set as critical levels.

Inputs
Lines 12-17 allow the indicator to be easily configured by accepting several inputs, as
shown:
kperiods := input("%K Time periods",5,1); kslowing :=
input("%K Slowing periods",3,1); dperiods := input("%D Time
periods",3,1); method := inputma("%D Method",S); expr :=
expression("Expression"); signalperiods := input("Buy/Sell
signal periods",200,1);
Three types of input are used here: input, inputma, and expression, which allow
the input of a number, a moving average type, and a data column respectively.
Note that each input is assigned to a variable. It is possible to use an input directly in a
formula, but it is recommended that the input is assigned to a variable. This makes the
script more readable, and also means that the result of the input can be used in several
places if necessary.
Each input includes a short but informative description. This text will be shown on the
Insert Indicator dialog. Lines 12-15 and 17 include a default value for the input. That is,
the number following the description. It's a good idea to supply a default value for every
possible input. Following the default is a minimum value for that input. By providing this
information, BullCharts can ensure that only sensible number are passed into the script.

The %K Line
Lines 20-21 show the actual calculation of the Stochastic Oscillator as we saw in the
simple example, except fixed numbers have been replaced with our input variables. The
result is assigned to the variable kay. Line 21 simply has the work kay. This has the effect
of returning the previous calculation as a plot - but it was first assigned to a variable, the
result can be used in later parts of the script. Put differently, any calculation that is not
assigned to a variable gets returned as a plot. An attribute on line 20 preceeds the result
and tells BullCharts the name of that plot. In this case %K.

136
Sample Indicator

The %D Line
[name=%D; linestyle=Dash]
ma(kay,dperiods,method);
Lines 23-24 describe the signal line, %D. The linestyle attribute is also added to make the
signal appear as a dashed line by default. Because the %K result had been assigned to a
variable, it can be re-used in the calculation of %D. Line 24 specifies that the result is a
moving average over %K, of the length specified by the input, and of the type specified by
the inputma.

Markers
Lines 26-31 describe two markers that indicate when significant events occur on the chart.
The linestyle=market attribute indicates that the next result should be interpreted as
a marker. Whenever the following result evaluates to true, a marker will be drawn. In this
case markers are drawn when the %K rises above 20 or falls below 80, among other
conditions. Note the use of a comment, in green, to visually separate the markers from
other parts of the script. Comments are a useful way of making a script more
understandable to others.

See Also
Sample Scripts

137
Troubleshooting
BullScript prevents you from entering a formula that has a mistake in it by displaying an
error message and asking you to correct the formula before proceeding. BullScript
generally does a very good job at detecting what kind of error a formula has.
BullScript will display an error code when it displays an error message. This is a three-
digit number which usually begins with ‘1’. See the full list of error codes.

See Also
Error Codes

139
Error Codes
When BullScript encounters an error it will give an error code. Use the list below to learn
more information about a particular error.
101
Some code was expected at a certain point, but none was found. This typically
happens if a formula stops in the middle without concluding. E.g. 1 +
102
An opening bracket was found, without a matching closing bracket. E.g. (1 + 2
103
A closing bracket was found, but it doesn't have a matching opening bracket. E.g.
1 + 2)
104
To the right of a dot, there was something other than a single variable name. E.g.
myformula.my variable. This is not legal since 'my' and 'variable' are
seen seperately by BullScript. You can’t have a variable name that contains
spaces.
105
To the left of a dot, there was something other than a formula found.
106
Something was used as a formula, but that formula has not been entered, and
there is no builtin function with that name. Perhaps you forgot to enter the
formula, or perhaps the formula name was mis-spelt.
107
A variable within a formula was accessed using formula.variable syntax, and
formula is a valid formula, but it doesn't contain a variable with the name given.
Maybe the you mis-spelt the variable name?
108
The script appears to be attempting to call a function, but the bracket syntax isn't
correct. Perhaps brackets don't match?
109
A function or formula was called, but the wrong number of parameters was
supplied. E.g. add(4) or add(5,4,8).

141
Getting Started with BullScript

110
A function or formula was called, and a non-constant parameter was supplied
where a constant parameter is required. E.g. mov(C,V).
This is illegal because the second parameter to mov must be constant.
Alternatively, this error can also be triggered if a constant is of the wrong value.
E.g. mov(C,-10).
This is illegal because a moving average can't be calculated over a negative
number of periods, and so the function guards against this.
111
An operator was logically expected but none was found. E.g. 1 2. Some kind of
operation is expected between '1' and '2' but there is nothing there.
112
Something was found which looks like it's meant to be a number, but it's not
correctly formatted. E.g. 1.2e or 1.22.4
113
A string wasn't closed properly before the end of the formula. Perhaps you forgot
to put in a closing quote? E.g. input("Enter the number of
periods,5,0,10)
114
A valid variable, formula, or function name was found, but there is no known
variable, formula, or function with that name. Perhaps you mis-spelt it, or forgot
to add in a formula earlier? E.g. myvariable := 5; myvaraible * 2
115
A variable with the same name was defined twice in the same formula. E.g.
myvariable := 5; myvariable := 2
116
A formula with the same name was entered twice.
117
To the left of the assignment operator, :=, there was something other than a valid
variable name. E.g. 5 + 4 := 9
118
A variable name was not in a correct format, it contained illegal characters, or is
a reserved language keyword.
119

142
Error Codes

A formula was entered which is empty of any plots or assignments.


120
You have tried to remove a formula, but it can't be removed, because other
formulae use it.
121
A comment isn’t closed before the end of a formula.

See Also
Troubleshooting

143
Index
A B
Abs function .......................................36 BarsSince function ............................. 27
Absolute Value....................................36 BBandBot function............................. 80
Accumulation Swing Index ................78 BBandTop function ............................ 80
Accumulation/Distribution .................79 Bear Harami ....................................... 52
ActTrade .............................................86 Bear Harami Cross ............................. 52
ActVest ...............................................87 Bearish Engulfing Pattern................... 56
AD function........................................79 Best Practices ................................... 137
Add function.......................................37 Big Black............................................ 53
ADX function .....................................79 Big White ........................................... 53
Alias attribute ............................. 13, 115 Black Body......................................... 53
AllFalse function ................................25 Black function .................................... 53
AllTrue function .................................26 Bollinger Bands.................................. 80
And .......................................................3 Bull Harami ........................................ 54
AnnualDividendPerShare variable .......5 Bull Harami Cross .............................. 54
AnyFalse function ..............................26 Bullish Engulfing Pattern ................... 56
AnyTrue function ...............................27 C
Arc Tangent ........................................37 C variable ............................................. 4
Aroon..................................................79 Category attribute ....................... 13, 115
AroonDown function..........................79 CCI function....................................... 82
AroonUp function...............................79 Ceiling function.................................. 38
AssetBacking variable ..........................5 Chaikin Accumulation/Distribution
Oscillator ....................................... 81
ASwing function.................................78
Chaikin’s Money Flow ....................... 81
ATan function .....................................37
Chande Momentum Oscillator ........... 82
ATR function ......................................80
Citation attribute......................... 13, 115
Attributes .................................... 13, 115
Close price............................................ 4
Average Directional Movement..........79
CMF function ..................................... 81
Average True Range ...........................80

145
Getting Started with BullScript

CMO function.....................................82 Ease of movement .............................. 84


CO function ........................................81 ElasticVolumeWeighted function ....... 93
Color attribute...................................121 EMV function..................................... 84
Comments...........................................12 EndPoint function............................... 93
Commodity Channel Index.................82 Engulfing Bear ................................... 56
Commodity Selection Index ...............83 Engulfing Bull .................................... 56
Correl function....................................38 EPS variable ......................................... 5
Cos function .......................................39 Error codes ....................................... 149
Cross function.....................................68 Exp function ....................................... 39
CSI function .......................................83 Exponential function .......................... 93
CurrentDividendAmount variable ........5 Expression function............................ 28
D F
Date function ......................................70 Falling Window .................................. 57
Dayofmonth function..........................70 Fib function ........................................ 40
DEMA function ..................................83 Fibonacci ............................................ 40
Description attribute ................... 13, 115 FillStyle attribute .............................. 124
Directional Movement Index..............84 FirstValue function ............................. 28
Displaying Text...................................21 Floor function ..................................... 40
Div function........................................39 Font attribute .............................. 13, 115
DividendCover variable........................5 FontSize attribute ....................... 13, 115
DividendPerShare variable ...................5 FontStyle attribute ...................... 13, 115
DividendYield variable.........................5 Forecast function ................................ 85
Doji.....................................................55 Forecast Oscillator.............................. 85
Doji Star..............................................55 ForecastOsc function.......................... 85
Double exponential moving average ..83 Formula function ................................ 29
DPS variable.........................................5 Frac function ...................................... 41
DX function........................................84 Fractal Dimension .............................. 85
E FractalDim function ........................... 85
EarningsPerShare variable....................5 Fractional Part .................................... 41
EarningsYield variable .........................5 Franked variable ................................... 5

146
Index

FrankedPercent variable .......................5 I


Functions ............................................18 If function........................................... 30
Fundamentals........................................5 IMI function ....................................... 88
Future function ...................................29 Industry variable................................... 5
G IndustryCode variable .......................... 5
GapDown function .............................68 IndustryGroup variable......................... 5
GapUp function ..................................68 Inertia function ................................... 88
GICS variable .......................................5 Input function ..................................... 32
Global Industry Classification System .5 InputDate function.............................. 71
Grave Stone Doji ................................57 InputMA function ............................... 32
GrossDividendAmount variable ...........5 InputROC function ............................. 33
H Inside function.................................... 69
H variable .............................................4 Int function ......................................... 41
Hammer ..............................................58 Intraday Momentum Index ................. 88
Hanging Man ......................................59 Introducing BullScript.......................... 1
High price .............................................4 Inverted Hammer................................ 59
Highest function .................................73 InvHammer function .......................... 59
HighestBars function ..........................74 K
HighestSince function ........................75 Keltner Channel.................................. 89
HighestSinceBars function .................75 KeltnerBot function............................ 89
Hist function .......................................30 KeltnerTop function............................ 89
Horzline attribute........................ 13, 115 Klinger Oscillator ............................... 90
Hour function .....................................71 KVO function ..................................... 90
Hull ActTrade .....................................86 L
Hull ActVest .......................................87 L variable.............................................. 4
HullAtRoar function...........................86 Last price .............................................. 4
HullRoad function ..............................87 Linear Regression............................... 42
HullRoar function...............................87 Linear Regression Slope..................... 42
Hurst Exponent...................................85 LinearReg function............................. 42
LineStyle attribute ............................ 126

147
Getting Started with BullScript

LinkedChart attribute.................. 13, 115 Minute function .................................. 72


LinRegSlope function.........................42 MO function ....................................... 92
Log function .......................................42 Mod function ...................................... 44
Long Legged Doji...............................60 Modulo ............................................... 44
Long Lower Shadow ..........................60 Momentum ......................................... 92
Long Upper Shadow...........................61 Money Flow Index ............................. 93
Low price..............................................4 Month function ................................... 72
Lowest function ..................................76 Morning Doji Star............................... 61
LowestBars function...........................76 Morning Star....................................... 62
LowestSince function .........................77 Moving Average ................................. 93
LowestSinceBars function..................77 MP function ........................................ 91
M Mul function....................................... 45
MA function .......................................93 N
MACD function..................................90 Name attribute ............................ 13, 115
MAMA function .................................91 Neg function....................................... 45
Market Facilitation Index ...................90 Negative Volume Index ...................... 95
MarketCap variable ..............................5 NetTangibleAssets variable .................. 5
MarketFacIndex function ...................90 Now function...................................... 72
MASS function...................................91 NTA variable ........................................ 5
Mass Index .........................................91 Number of trades .................................. 4
Max function ......................................43 NVI function ...................................... 95
MDI function ......................................92 O
Median function..................................91 O variable ............................................. 4
Median Price.......................................91 OBV function ..................................... 95
MESA Adaptive Moving Average ......91 On Balance Volume ............................ 95
MFI function.......................................93 Open price ............................................ 4
MID function ......................................91 Operators .............................................. 3
Midpoint .............................................91 Or 3
Min function .......................................44 Order of operations............................... 3
Minus Directional Movement (-DI)....92 OSCP function.................................... 99

148
Index

OSCV function ................................. 111 Q


Outside function .................................69 Qstick function ................................. 101
P R
Parabolic SAR ....................................96 Rally ................................................. 101
Param function....................................33 Rally function ................................... 101
PDI function .......................................98 Rally with Volume ............................ 102
PE variable ...........................................5 RallyWithVol function...................... 102
Peak function ......................................96 Random Walk Index ......................... 102
PeakBars function...............................97 Range Indicator ................................ 102
PER function ......................................97 RangeIndicator function ................... 102
PERatio variable...................................5 Rate of Change ................................. 102
Performance........................................97 RateOfChange function .................... 102
Period attribute ........................... 13, 115 Reaction............................................ 103
Pi constant ..........................................46 Reaction function ............................. 103
Plus Directional Movement (+DI) ......98 Reaction with Volume ...................... 103
Positive Volume Index........................98 ReactionWithVol function ................ 103
Power function....................................46 Relative Strength Index .................... 104
Previous function................................34 Relative Volatility Index................... 104
Price Channel......................................98 Rising Window ................................... 63
Price Oscillator ...................................99 ROC function ................................... 102
Price Volume Trend ............................99 Round function ................................... 46
PriceChannelHigh function ................98 RSI function ..................................... 104
PriceChannelLow function .................98 R-Squared......................................... 105
ProjBandBot function.......................100 RSquared function............................ 105
ProjBandTop function.......................100 RVI function ..................................... 104
Projection Bands...............................100 RWI function .................................... 102
Projection Oscillator .........................100 S
ProjOsc function...............................100 Sample Scripts.......................... 139, 141
PVI function .......................................98 SAR function...................................... 96
PVT function ......................................99 Second function.................................. 73

149
Getting Started with BullScript

Sector variable ......................................5 TimeSeries function............................ 93


SectorIndex variable .............................5 TotalIssue variable................................ 5
Security keyword..................................5 Trades ................................................... 4
Shaven Bottom ...................................63 Transparency attribute ................ 13, 115
Shaven Head.......................................64 TrendLine function ............................. 50
Shooting Star ......................................64 Triangular function ............................. 93
Simple function ..................................93 TRIX function .................................. 108
Sin function ........................................47 Trough function ................................ 108
SortPlots attribute ....................... 13, 115 TroughBars function......................... 109
Sqrt function .......................................47 TSF function..................................... 107
Square root .........................................47 Turnover ............................................... 4
Standard Deviation .............................48 Tweezer Bottoms ................................ 66
Standard Eeviation..............................48 Tweezer Tops...................................... 66
StDev function....................................48 Typical function................................ 109
StEyx function ....................................48 Typical Price..................................... 109
Stoch function...................................106 U
Stochastic Momentum Index ............105 Ultimate function.............................. 110
Stochastic Oscillator .........................106 Ultimate Oscillator ........................... 110
StochMomentum function ................105 Usage attribute............................ 13, 115
Sub function .......................................49 V
SubIndustry variable.............................5 V variable ............................................. 4
Sum function ......................................49 Value..................................................... 4
Swing function..................................106 ValueWhen function ........................... 35
Swing Index......................................106 Var function ...................................... 110
T Variable function ................................ 93
Target attribute..................................133 Variance............................................ 110
TEMA function.................................107 Vertical Horizontal Filter.................. 111
Three Black Crows .............................65 VHF function.................................... 111
Three White Soldiers ..........................65 Visible attribute .......................... 13, 115
Time Series Forecast.........................107 Vol function ...................................... 111

150
Index

Volatility ........................................... 111 WilderS function .............................. 112


Volume..................................................4 Wilder's Smoothing .......................... 112
Volume Oscillator ............................. 111 WillA function .................................. 113
VolumeAdjusted function ...................93 Williams' %R.................................... 113
W Williams' A/D ................................... 113
Wait function ......................................35 WillR function .................................. 113
WC function ..................................... 112 Y
Weighted Close................................. 112 Year function ...................................... 73
Weighted function...............................93 Z
White Body.........................................67 ZeroLag function................................ 93
White function ....................................67 ZigZag function................................ 113
Width attribute............................ 13, 115

151

Вам также может понравиться