Register Account

Algorithmic Trading

API Reference

This JavaScript API Reference is your instruction manual for writing both trading algorithms and technical indicators. If you're getting started, take a look at Writing Your Algorithms and Writing Your Technical Indicators for an overview.



Handlers


onTick function

Your onTick function will fire on every price update of the instrument you are running your backtest or trading session on.

Example

function onTick() {
    // Runs on every tick of the instrument your session is running on
}

If your algorithm runs on multiple instruments, you can also assign a tick handler to these.

INSTRUMENTS["EUR/USD:FXCM"].onTick = function () {
    // Runs on every tick of EUR/USD:FXCM
};

onIntervalClose function

The onIntervalClose function fires when each price bar closes.

Examples

function onIntervalClose () {
    // Runs every bar close (default instrument and interval of session)
}

You can also assign an interval close handler to multiple timeframe intervals. Shorter timeframes fire first. Available are M1, M2, M5, M10, M15, M30, H1, H2, H4, H8, H12 and D1. This is only available to algorithms, not indicators.

M1.onIntervalClose = function () {
    // Runs every 1 minute bar close (default instrument)
};
H2.onIntervalClose = function () {
    // Runs every 2 hour bar close (default instrument)
};

These can also be assigned to multiple instruments.

// Assign instrument to a variable for convenience
var EURUSD = INSTRUMENTS["EUR/USD:FXCM"];

EURUSD.onIntervalClose = function () {
    // Runs every EUR/USD:FXCM bar close (default interval of session)
};
EURUSD.M1.onIntervalClose = function () {
    // Runs every EUR/USD:FXCM 1 minute bar close
};

The onIntervalClose for any instrument will only fires when there is a closing bar, i.e. when ticks have been received during the previous interval. The first tick of the new bar signals the close.



Current Price


TIME object

In onTick, the time of the current tick. In onIntervalClose, the closing time of the bar. Represented as a JavaScript Date instance. See Date - JavaScript | MDN.


BID number

In onTick, the bid price of the current tick. In onIntervalClose, the bid price of the tick opening the new bar. Unavailable to indicators.

Examples

BID; // Current bid price of default instrument
INSTRUMENTS["EUR/USD:FXCM"].BID; // Current bid price of EUR/USD:FXCM

ASK number

In onTick, the ask price of the current tick. In onIntervalClose, the ask price of the tick opening the new bar. Unavailable to indicators.

Examples

ASK;
INSTRUMENTS["EUR/USD:FXCM"].ASK;

MID number

The average of the BID and ASK prices. Unavailable to indicators.

Examples

MID;
INSTRUMENTS["EUR/USD:FXCM"].MID;

SPREAD number

The current spread (difference between ask and bid prices), represented in pips. The precision of this value will depend on the pip size of the instrument and the precision at which the price is quoted. Typically this would have been an integer, though brokers generally now offer fractional pip precision, resulting in this value having 1 decimal place. Unavailable to indicators.

Example

SPREAD;
INSTRUMENTS["EUR/USD:FXCM"].SPREAD;


Instrument


INSTRUMENTS object

By default, API identifiers for Handlers, Current Price, Positions and Price Bars will return data for, or act on, the instrument you select when firing up new backtests or starting live trading sessions.

You can also access multiple instruments in your algorithm, using the INSTRUMENTS object.

Examples

Each instrument is available as a property of INSTRUMENTS and can be retrieved using bracket notation, returning an instrument object.

INSTRUMENTS["EUR/USD:FXCM"];

Where applicable, API identifiers specific to that instrument are then available on the object. Some examples:

INSTRUMENTS["EUR/USD:FXCM"].onIntervalClose = function () {
    // Runs every EUR/USD:FXCM bar close
};
INSTRUMENTS["EUR/USD:FXCM"].BID;                      // Current EUR/USD:FXCM bid price
INSTRUMENTS["EUR/USD:FXCM"].openPosition("BUY", ...); // Open a long position on EUR/USD:FXCM
INSTRUMENTS["EUR/USD:FXCM"].OPEN;                     // Open price of current or closing EUR/USD:FXCM bar
INSTRUMENTS["EUR/USD:FXCM"].prices(n);                // Closing EURUSD mid prices since n intervals ago

You may want to assign to a variable to avoid repetition. If you do so, please note that this must be done in the global scope, outside of any functions, for the instrument to be imported. It will then be available throughout your script.

var EURUSD = INSTRUMENTS["EUR/USD:FXCM"];
EURUSD.PRECISION;                                     // Precision of EUR/USD:FXCM
EURUSD.PIP_SIZE;                                      // Pip size of EUR/USD:FXCM

function onIntervalClose () {
    EURUSD.ASK;                                       // Current EUR/USD:FXCM ask price
    EURUSD.openPosition("SELL", ...);                 // Open a short position on EUR/USD:FXCM
    EURUSD.M30.HIGH;                                  // High price of current or closing EUR/USD:FXCM 30 minute bar
    EURUSD.H1.prices(n);                              // Closing EURUSD mid prices since n hourly intervals ago
}

PRECISION number

The precision, in decimal places, that prices for the instrument are quoted. Aliases INSTRUMENT.PRECISION.

Examples

PRECISION; // Precision of default instrument
INSTRUMENTS["EUR/USD:FXCM"].PRECISION; // Precision of EUR/USD:FXCM

PIP_SIZE number

This varies from instrument to instrument. On forex pairs this will typically be 0.0001, with the exception of Yen pairs which have a pip size of 0.01. Useful whenever you want to calculate a price in terms of pips. Aliases INSTRUMENT.PIP_SIZE.

Examples

PIP_SIZE;
INSTRUMENTS["EUR/USD:FXCM"].PIP_SIZE;

Open a long position, setting a stop loss 15 pips below bid price.

openPosition("BUY", {
    quantity: 10000,
    stopLoss: BID - (15 * PIP_SIZE)
});

INSTRUMENT object

An object representing the instrument currently being traded, or running indicators against. Usage: INSTRUMENT.BASE, INSTRUMENT.QUOTE, INSTRUMENT.PRECISION, INSTRUMENT.PIP_SIZE.

Properties

BASE string
The base, or dealt, currency of the instrument being traded. e.g. `'EUR'` for EUR/USD.
QUOTE string
The quote, or term, currency of the instrument being traded.
PRECISION number
The precision, in decimal places, that prices for the instrument are quoted.
PIP_SIZE string
The size of a pip. See PIP_SIZE

Example

BASE; // Base currency of default instrument
QUOTE; // Quote currency of default instrument
INSTRUMENTS["EUR/USD:FXCM"].BASE; // EUR
INSTRUMENTS["EUR/USD:FXCM"].QUOTE; // USD


Session


INTERVAL string

The interval timeframe your session is running on. This is set when you run a new backtest or live trading session and is the period on which your onIntervalClose function fires. Will be M1 minute, M2 2 minute, M5 5 minute, M10 10 minute, M15 15 minute, M30 30 minute, H1 hourly, H2 2 hour, H4 4 hour, H8 8 hour, H12 12 hour or D1 daily.


INTERVAL_MS number

The interval timeframe your session is running on, expressed in milliseconds.



Account


BALANCE number

Your account balance, in account currency. Unavailable to indicators.


EQUITY number

Your account balance plus the unrealized profit of any open positions, in your account currency. Unavailable to indicators.


UNREALIZED_PROFIT number

Your unrealized profit from any open positions, in your account currency. Unavailable to indicators.


USED_MARGIN number

The total used margin of your open positions. The used margin reflects the leverage offered by the broker and is the amount of equity you need for the broker to keep your positions open. Represented in your account currency. Unavailable to indicators.


AVAILABLE_MARGIN number

Your equity minus the total used margin of your open positions. If this drops to zero you will receive a margin call from your broker and any positions you have open will be closed. Unavailable to indicators.



Positions


openPosition openPosition(side, options)

Creates a market order, opening a position.

Parameters

side string
Value must be one of "BUY" to buy at the current ask price, opening a long position, or "SELL", to sell at the current bid price, opening a short position. Can also be expressed as "LONG" or "SHORT" if you prefer.
options object
An object whose properties define the trade parameters:
quantity number
The amount to trade in units of the base currency. For example, if you set the quantity at 10,000 and buy EUR/USD, you are buying €10,000 with an amount of USD as determined by the price. Generally this must be in multiples of 1000 as this is the smallest trade the brokers will accept. Quantity can alternatively be expressed as lots, riskPercentage or riskAmout.
or lots number
Quantity can alternatively be specified in terms of lots. One lot is 100,000 units, so if you set lots to 4 you are trading 400,000 or the base currency.
or riskPercentage number
Rather than specifying an absolute quantity, you can specify quantity as the amount of your account balance you wish to risk. The quantity will be calculated for you by taking into account your account balance and the distance between the opening price and your stop loss. Note that this is an approximation - where your account currency is not the same as the quote currency of the instrument you are trading, you are subject to movement of the conversion currency or currencies. You are also subject to price slippage in trade execution. Stop loss must be specified.
or riskAmount number
Similarly, you can specify the amount you want in units of your account currency. For example, if you have a USD account and set the riskAmount to 10, you are risking approximately 10.00USD should the position close if stop loss is met. Outcome is approximate as with riskPercentage. Stop loss must be specified.
stopLoss number
The price at which to close out a losing position. We recommend that a stop loss is always set. The position will close if price hits the stop loss value (bid price for long positions and ask price for short positions).
or stopLossPips number
The stop loss can also be set in terms of pips. This is the distance below the ask price for long positions, or above the bid price for short positions, at which to set the stop loss.
trailingStop number
The price at which to set a trailing stop. Trailing stops will track price as it moves in the direction of your position. A trailing stop on a long position will adjust upwards as price moves upwards, thereby protecting your profit, and remain fixed if price falls. The vice versa is true for short positions.
or trailingStopPips number
Trailing stops can also be set in terms of pips. This is the distance below the ask price for long positions, or above the bid price for short positions, at which to set the trailing stop.
takeProfit number
The target price at which to close a profitable position. The position will close if price hits the take profit value (bid price for long positions and ask price for short positions).
takeProfitPips number
Take profit can also be set in terms of pips. This is the distance above the ask price for long positions, or below the bid price for short positions, at which to set the take profit.

Examples

Open a long position of quantity 10,000, setting stop loss and take profit.

openPosition("SELL", {
    lots: 0.1,
    stopLoss: ASK - 0.0015,
    takeProfit: ASK + 0.0025
});

Open a long position that risks 2% of your account balance.

openPosition("BUY", {
    riskPercentage: 2,
    stopLoss: BID - 0.0015,
    takeProfit: BID + 0.0025
});

When expressed as a risk percentage, the quantity is automatically calculated on the basis of how much the position would lose if stop loss was reached in relation to your opening account balance. It therefore requires of course that you have set a value for stop loss.

In the example above, if you had a USD account with a balance of $10,000, you would be risking $200 (2% of $10,000). If you were trading EUR/USD and the price was bid 1.3000 and ask 1.3005, the quantity would be calculated to be 100,000, creating the following scenario if stop loss were reached:

BUY 100,000 EUR/USD at ask 1.3005 with $130,050

Price hits stop loss at 1.2985, i.e. 1.3000 - 0.0015

SELL 100,000 EUR/USD at bid 1.2985 for $129,850

Results in loss of $200, i.e. $130,050 - $129,850


Open a long position that risks an absolute amount of your account balance. Again, the position quantity is calculated automatically.
openPosition("BUY", {
    riskAmount: 200,
    stopLoss: BID - 0.0015,
    takeProfit: BID + 0.0025
});

You can also open positions on any instrument, regardless of the instrument your session is trading on. Use any of the following equivalent formats:
var EURUSD = INSTRUMENTS["EUR/USD:FXCM"];

EURUSD.openPosition("BUY", {
    quantity: 10000
});
openPosition(EURUSD, "BUY", {
    quantity: 10000
});
openPosition("EUR/USD:FXCM", "BUY", {
    quantity: 10000
});

closeAllPositions closeAllPositions()

Closes all open positions. Aliases OPEN_POSITIONS.closeAll().


OPEN_POSITIONS_COUNT number

The number of positions you currently have open. Unavailable to indicators.


OPEN_POSITIONS object

A collection representing your currently open positions. Unavailable to indicators.

Properties

length number
An integer representing the number of open positions. Equivalent to OPEN_POSITION_COUNT. Usage: OPEN_POSITIONS.length

Methods

closeAll()
Closes all open positions. Usage: OPEN_POSITIONS.closeAll()
get(id)

Returns the position from the collection with broker identifier `id`.

Parameters

id string
The identifier of the position to return.
at(index)

Returns the position from the collection at `index`.

Parameters

index number
The index of the position to return. Zero based, the first being the first position to open.
size()
Returns OPEN_POSITIONS.length. Usage: OPEN_POSITIONS.size()
each(iterator)

Iterates over each position in collection passing each in turn to an iterator function. This is aliased with forEach if that is more familiar to you.

Parameters

iterator function
This gets called for each position and is passed (position, index, collection). position is a position object, index is the array index of the position and collection is the entire positions collection.

Example

Use a moving take profit target to close positions, in this case a Simple Moving Average envelope:

var targetEnvelope = 15 * PIP_SIZE;
OPEN_POSITIONS.each(function (position) {
    if (position.DIRECTION === "LONG" && BID > sma(period) \* (1 + targetEnvelope)) {
        position.close();
    } else if (position.DIRECTION === "SHORT" && ASK < sma(period) \* (1 - targetEnvelope)) {
        position.close();
    }
});
map(iterator)

Returns a new array of values by mapping each position through the iterator function.

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. Should return the new mapped value for this position.
reduce(iterator, initialValue)

Reduces positions list into a single value. See Array.prototype.reduce() - JavaScript | MDN

Parameters

iterator function
This gets called for each position and is passed (value, position). value is the accumulated value. position is a position object.

Example

Calculate total unrealized pips gained:

var unrealizedPips = OPEN_POSITIONS.reduce(function (value, position) {
    var pips;
    if (position.DIRECTION === "LONG") {
        pips = (BID - position.OPEN_PRICE) / PIP_SIZE;
    } else {
        pips = (position.OPEN_PRICE - ASK) / PIP_SIZE;
    }
    return value += pips;

}, 0);

find(iterator)

Returns the first position that the iterator returns true for. The list will stop being traversed once position is found.

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. Should return true for the position searched for.
filter(iterator)

Returns an array of the positions that pass the iterator test.

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. Should return true if the position is to be included in the returned array.

Example

Get a list of all open positions with profit greater than 10 (units of account currency):

OPEN_POSITIONS.filter(function (position) {
    return position.PROFIT > 10;

}); // or with ES6 OPEN_POSITIONS.filter((position) => position.PROFIT > 10);

where(properties)

Returns an array of the positions that match the set of properties.

Parameters

properties object
An object with properties and values to match against.

Example

Get a list of all open positions trading on FXCM's EUR/USD that are long:

OPEN_POSITIONS.where({
    INSTRUMENT_ID: "EUR/USD:FXCM",
    DIRECTION: "LONG"

});

findWhere(properties)

The same as `where`, but returns only the first match or `undefined` if none matched.

Parameters

properties object
An object with properties and values to match against.
reject(iterator)

Returns an array excluding the positions that pass the iterator test. The opposite of filter

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. Should return true if the position is to be exluded from the returned array.
every(iterator)

Returns true if the iterator test returns true for every position.

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. Must all return true for the return value to be true.
some(iterator)

Returns true if the iterator test returns true for some (or any) position.

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. If any return true the return value will be true.
pluck(property)

Returns an array that contains the extracted list of position property values.

Parameters

property string
The property that should be extracted, e.g. "openPrice"
max(iterator)

Returns the position that the iterator returns the highest value for.

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. This should return that value to be compared.
min(iterator)

Returns the position that the iterator returns the lowest value for.

Parameters

iterator function
This gets called for each position and is passed (position). position is a position object. This should return that value to be compared.

Position

A object representing a position, returned by getPosition(id) and contained in the OPEN_POSITIONScollections.

Properties

ID string
The broker assigned identifier of the position.
SESSION_ID string
The identifier of the session that opened the position.
INSTRUMENT_ID string
The identifier of the instrument the position is traded on.
OPEN_TIME date
A date object set to the timestamp of the last tick at position open.
OPEN_PRICE number
Opening price of the position. Will be the ask price if the position is long, or the bid price if it is short.
QUANTITY number
The size of position in the instrument's base currency.
DIRECTION string
"LONG" if opened with a buy order, "SHORT" if opened with a sell order.
STATUS string
The status of the position. Either "OPEN" or "CLOSED".
STOP_LOSS number
The price of any stop loss target order attached to the position.
TAKE_PROFIT number
The price of any take profit target order attached to the position.
USED_MARGIN number
The used margin of the position, i.e. the amount of equity you require for the broker to keep the position open.
CLOSE_TIME date
A date object set to the timestamp of the last tick at position close.
CLOSE_PRICE number
Closing price of the position. Will be the bid price if the position was long, or the ask price if it was short.
PROFIT number
If the position is open, this is the unrealized profit in your account currency, as calculated by the system. On closed positions, this is the final profit as supplied by the broker. Not enumerable while open.

Methods

close()
Closes the position.


Price Bars

A suite of constants and methods for accessing both the current and historical price bars (or candles). A price bar is an object containing open, high, low and close values, representing price movement through a given interval, as commonly represented on charts.

PRICE object

PRICE is an object representing the price bar (candlestick), containing both bid and ask OHLC prices and their mids. When used in the onTick function it refers to the current bar. In onIntervalClose it refers to the the closing bar. See also price() below for a range of methods to retrieve historical price.

Example

PRICE.TIME          // The bar's open time

PRICE.MID.OPEN      // The open mid price
PRICE.MID.HIGH      // The high mid
PRICE.MID.LOW       // The low mid
PRICE.MID.CLOSE     // The mid close

PRICE.BID.OPEN      // The open bid price
PRICE.BID.HIGH      // The high bid
PRICE.BID.LOW       // The low bid
PRICE.BID.CLOSE     // The bid close

PRICE.ASK.OPEN      // The open ask price
PRICE.ASK.HIGH      // The high ask
PRICE.ASK.LOW       // The low ask
PRICE.ASK.CLOSE     // The ask close

PRICE.OPEN          // Shorthand alias for PRICE.MID.OPEN
PRICE.HIGH          // Shorthand alias for PRICE.MID.HIGH
PRICE.LOW           // Shorthand alias for PRICE.MID.LOW
PRICE.CLOSE         // Shorthand alias for PRICE.MID.CLOSE

OPEN number

The opening mid price of the current, or closing, bar. Aliases PRICE.OPEN and PRICE.MID.OPEN.

Examples

Defaults to the instrument and timeframe interval you are running your session on.

OPEN;

...but also available on multiple instruments and intervals.

M15.OPEN;
INSTRUMENTS["EUR/USD"].OPEN;
INSTRUMENTS["EUR/USD"].M15.OPEN;

HIGH number

The highest mid price of the current, or closing, bar. Aliases PRICE.HIGH and PRICE.MID.HIGH.

Examples

Defaults to the instrument and timeframe interval you are running your session on.

HIGH;

...but also available on multiple instruments and intervals.

M15.HIGH;
INSTRUMENTS["EUR/USD"].HIGH;
INSTRUMENTS["EUR/USD"].M15.HIGH;

LOW number

The lowest mid price of the current, or closing, bar. Aliases PRICE.LOW and PRICE.MID.LOW.

Examples

Defaults to the instrument and timeframe interval you are running your session on.

LOW;

...but also available on multiple instruments and intervals.

M15.LOW;
INSTRUMENTS["EUR/USD"].LOW;
INSTRUMENTS["EUR/USD"].M15.LOW;

CLOSE number

The closing mid price of the current, or closin,g bar. Aliases PRICE.CLOSE and PRICE.MID.CLOSE.

Examples

Defaults to the instrument and timeframe interval you are running your session on.

CLOSE;

...but also available on multiple instruments and intervals.

M15.CLOSE;
INSTRUMENTS["EUR/USD"].CLOSE;
INSTRUMENTS["EUR/USD"].M15.CLOSE;

price price(n)

Retrieves a single point of historical price bar data. In onIntervalClose, returns the mid close price n intervals ago for the interval timeframe you are running your backtest or trading session on.

Parameters

n number
Optional. The number of intervals ago. Can specify as negative integer. If omitted or `0`, returns the most recent close.
or n date
Optional. Retrieves price bar data at time (JavaScript date) provided. Will return `null` if there is no bar at that time.

Example

price also has a range of methods for retrieving the open, high, low and close values of the mid, bid and ask prices. These have shorter forms that default to mid and close.

Perhaps best shown by example:

// Shorthand retrieves mid close price
price(n);                       // Same as price.mid.close(n), price.close(n) and price.mid(n)

// Equivalent to close price methods
price.mid(n);                   // Same as price.mid.close(n) and price.close(n)
price.bid(n);                   // Same as price.bid.close(n)
price.ask(n);                   // Same as price.ask.close(n)

// Equivalent to mid price methods
price.open(n);                  // Same as price.mid.open(n)   
price.high(n);                  // Same as price.mid.high(n)
price.low(n);                   // Same as price.mid.low(n)
price.close(n);                 // Same as price.mid.close(n)
price.ohlc(n);                  // Same as price.mid.ohlc(n)

// Mid price (bid/ask average) n intervals ago
price.mid.open(n);              // Mid open price
price.mid.high(n);              // Mid high price
price.mid.low(n);               // Mid low price
price.mid.close(n);             // Mid close price
price.mid.ohlc(n);              // Mid price OHLC object. Has properties OPEN, HIGH, LOW and CLOSE

// Bid price n intervals ago
price.bid.open(n);              // Bid open price
price.bid.high(n);              // Bid high price
price.bid.low(n);               // Bid low price
price.bid.close(n);             // Bid close price
price.bid.ohlc(n);              // Bid prices OHLC object

// Ask price n intervals ago
price.ask.open(n);              // Ask open price
price.ask.high(n);              // Ask high price
price.ask.low(n);               // Ask low price
price.ask.close(n);             // Ask close price
price.ask.ohlc(n);              // Ask prices OHLC object

// All of the above accept n as a date
price(new Date("2015-01-01"))   // Mid close price at 2015-01-01T00:00:00Z (or null)

// Notes
price() === price(0);           // Defaults to zero index, or most recent close
price(5) === price(-5);         // Depending on preference

You can also grab price bar data for various interval timeframes other than the one you are running your backtest or trading session on. Some examples below.

M1.price(n);                    // Closing mid price n 1 minute intervals ago
M30.price.mid(n);               // Closing mid price n 30 minute intervals ago
H12.price.bid.close(n);         // Closing bid price n 12 hourly intervals ago

Available timeframes are M1 minute, M2 2 minute, M5 5 minute, M10 10 minute, M15 15 minute, M30 30 minute, H1 hourly, H2 2 hour, H4 4 hour, H8 8 hour, H12 12 hour and D1 daily.

Additionally, you can retrieve price from any instrument.

var EURUSD = INSTRUMENTS["EUR/USD:FXCM"];
EURUSD.price(n);                 // Closing EURUSD mid price n default timeframe intervals ago
EURUSD.M30.price.mid(n);         // Closing EURUSD mid price n 30 minute intervals ago
EURUSD.H12.price.bid.close(n);   // Closing EURUSD bid price n 12 hourly intervals ago

prices prices(n)

Retrieves a range of historical price bar data. In onIntervalClose, returns an array of the n most recent mid close prices for the interval timeframe you are running your backtest or trading session on. Array is in reverse chronological order, i.e. value at index 0 is for the most recent price bar.

Parameters

n number
The number of recent intervals to return. Can specify as negative integer. Must absolute to 1 or greater.

Examples

As with price above, prices has a range of methods for retrieving specific side and bar prices.

// Shorthand retrieves mid close prices
prices(n);                      // Same as prices.mid.close(n), prices.close(n) and prices.mid(n)

// Equivalent to close prices methods
prices.mid(n);                  // Same as prices.mid.close(n) and prices.close(n)
prices.bid(n);                  // Same as prices.bid.close(n)
prices.ask(n);                  // Same as prices.ask.close(n)

// Equivalent to mid prices methods
prices.open(n);                 // Same as prices.mid.open(n)   
prices.high(n);                 // Same as prices.mid.high(n)
prices.low(n);                  // Same as prices.mid.low(n)
prices.close(n);                // Same as prices.mid.close(n)
prices.ohlc(n);                 // Same as prices.mid.ohlc(n)

// Mid prices (bid/ask average) array of n intervals
prices.mid.open(n);             // Mid open prices
prices.mid.high(n);             // Mid high prices
prices.mid.low(n);              // Mid low prices
prices.mid.close(n);            // Mid close prices
prices.mid.ohlc(n);             // Mid price OHLC objects. Has properties OPEN, HIGH, LOW and CLOSE

// Bid prices array of n intervals
prices.bid.open(n);             // Bid open prices
prices.bid.high(n);             // Bid high prices
prices.bid.low(n);              // Bid low prices
prices.bid.close(n);            // Bid close prices
prices.bid.ohlc(n);             // Bid price OHLC objects

// Ask prices array of n intervals
prices.ask.open(n);             // Ask open prices
prices.ask.high(n);             // Ask high prices
prices.ask.low(n);              // Ask low prices
prices.ask.close(n);            // Ask close prices
prices.ask.ohlc(n);             // Ask price OHLC objects

// Notes
prices(5) === prices(-5);        // Depending on preference

As with the price method, you can also retrieve historical price bar data for timeframes other than your session default.

M1.prices(n);                    // Closing mid prices since n 15 minute intervals ago
H30.prices.bid(n);               // Closing bid prices since n hourly intervals ago
H4.prices.low(n);                // Low mid prices since n 4 hourly intervals ago
H12.prices.bid.close(n);         // Closing bid prices since n 12 hourly intervals ago
D1.prices.ask.ohlc(n);           // OHLC ask price objects since n daily intervals ago

...and from any instrument.

var EURUSD = INSTRUMENTS["EUR/USD:FXCM"];
EURUSD.prices(n);                // Closing EURUSD mid prices since n default timeframe intervals ago
EURUSD.M30.prices.mid(n);        // Closing EURUSD mid prices since n 30 minute intervals ago
EURUSD.H12.prices.bid.close(n);  // Closing EURUSD bid prices since n 12 hourly intervals ago

or prices prices(from[, to])

The alternative form of prices() takes a JavaScript date as the first argument to specify the range to return price bar data from.

Parameters

from date
Returns available intervals from date specified (inclusive).
to number
Optional. When specified as a number, `to` is the duration, in milliseconds, of bar data to return.
or to date
Optional. When specified as a date, bar data up to this time will be returned. Defaults to current time.

Example

All of the methods in the previous example accept n as a date and can take a second argument to specify a range.

prices(new Date("2015-01-01")); // Mid close prices from 2015-01-01T00:00:00Z to now
prices(new Date("2015-01-01T10:00:00"), 60*60*1000); // 1 hour of mid close prices from 2015-01-01T10:00:00Z
prices(new Date("2015-01-01T12:00:00"), new Date("2015-01-05T00:00:00")); // Mid close prices between dates supplied
M30.prices(new Date("2015-01-01T12:00:00"), 60*60*1000);
INSTRUMENTS["EUR/USD:FXCM"].H1.prices(new Date("2015-01-01T12:00:00"));


Sources


SOURCES object

Millions of finance and economic data series from our providers, Quadrant and Quandl, are available for you to use directly in your algorithms.

You can browse and search for these in the Data Sources page. Here you'll find an ID for each series. They are then available in your script on the SOURCES object and can be accessed by using bracket notation with the ID.

Example

The following each return a source object:

SOURCES["Quandl:WIKI:GOOG"];            // End of day Google stock prices from Quandl
SOURCES["Quadrant:ZlIz5q:SGE_USAM1"];   // Federal Reserve money supply from Quadrant

Many of the data series are freely available. The others are marked 'premium'. You'll need to provide an API key from Quadrant and Quandl in your 'My Account' screen.


Source object

A source object represents a single data series and provides a fetch() method for retrieving the data and properties to access meta information about the data and the data itself.

Methods

fetch()

Fetches the data from the provider.

To populate the data source, you'll need to call this method. It is important to call only as frequently as you expect the data to update, often only daily, as your algorithm execution will be halted as the data is fetched.

Example

Fetch End of day Google stock prices from Quandl once daily.

// Assign data series to a variable for convenience
var GOOG = SOURCES["Quandl:WIKI:GOOG"];

// Fetch data on daily interval close D1.onIntervalClose = function () { GOOG.fetch(); }

// Access data on minute interval close M1.onIntervalClose = function () { GOOG.FIELDS; // An array of labels for each data field GOOG.DATA; // An array containing the raw data GOOG.DATA[0]; // The most recent data item is the first item of the array }

Properties

ID string
The identifier of the data series.
PROVIDER string
The name of the provider.
NAME string
The name or description of the data series.
FIELDS array

An array of labels for each data field.

Example

SOURCES["Quandl:WIKI:GOOG"].FIELDS;
// ["Date", "Open", "High", "Low", "Close", "Volume", "Ex-Dividend", "Split Ratio"]
DATA array

An array containing the series data itself, in descending chronological order.

Example

SOURCES["Quandl:WIKI:GOOG"].DATA;
// [
//   ["2015-10-28", 707.33, 712.98, 703.08, 712.95, 2166114, 0, 1],
//   ["2015-10-27", 707.38, 713.62, 704.55, 708.49, 2250799, 0, 1],
//   ["2015-10-26", 701.55, 719.15, 701.26, 712.78, 2696691, 0, 1],
//   ...
// ]

SOURCES["Quandl:WIKI:GOOG"].DATA[0]; // ["2015-10-28", 707.33, 712.98, 703.08, 712.95, 2166114, 0, 1]

SOURCES["Quandl:WIKI:GOOG"].DATA[0][1]; // 707.33

FREQUENCY string
The frequency of the data points.
START string
The date of the earliest data point.
END string
The date of the most recent data point.
COUNT number
The number of data points.
SYNCED date
The time the data was last fetched.



Debugging


log log(value[, ..., valueN])

Write a value or series of values to the log output. The log output is available beneath backtest results once it has completed and in your live session views. You can alternatively use console.log(); if this is more familiar to you.

Parameters

value[, ..., valueN]
The value(s) to be logged.

plot plot(name, value[, ..., valueN])

The plot function offers a rich suite of charting functionality providing a visual alternative to console logging in backtesting. Each plot can draw one or several series. Each series can overlay the price chart or be drawn onto its own study and each can be drawn on the same y-axis as the price, or on an opposite axis where they have a different scale. Note that price charts are drawn at interval resolution - the value of the last plot will be drawn each interval close.

Note that plot() is not available to technical indicator scripts. The values expected by plot take the same format as values you return from your technical indicator onIntervalClose() function.

Parameters

name string
The name of the line chart series.
value number
The value to be plotted. Passing a value as a number (with no configuration options) will default to a price chart overlay.
or value array
Passing an array of two numbers will plot an area range.
or value object
Passing an object allows you to supply configuration for the series.

Properties

Where a value passed to plot() is an object, it should have the following properties:

color string
Optional. The color string can contain any valid css color value. See MDN | CSS Color. For example "red" or "#FF0000".
dashStyle string
Optional. Available options are "Solid", "ShortDash", "ShortDot", "ShortDashDot", "ShortDashDotDot", "Dot", "Dash", "LongDash", "DashDot", "LongDashDot" and "LongDashDotDot".
lineWidth number
Pixel width of the series line(s).
name string
Optional. The name of the series defaults to the name of the overall plot as pass to plot() as the first argument. As a plot can contain multiple series, you can override the name of each by supplying one here.
type string
Optional. Specifies the type of series. Available options are "area", "areaspline", "bar", "line" or "spline". Defaults to "spline". Where the value is an array of two numbers, available types are "arearange", "areasplinerange" and "columnrange". In this case the type defaults to "areasplinerange".
opposite boolean
Optional. If true, the series will use a separate right hand side y-axis. Use when the series should overlay the price chart or an existing study but has a different scale. Defaults to false.
precision number
Optional. The number of decimal places to round to for display in the hover tooltip.
overlay boolean
Optional. If false, the series will be drawn onto a separate study y-axis beneath the price chart. Defaults to true.
value number
The only required property.
or value array
Can also be an array of 2 numbers to describe an area range.

Additional options can be found in HighStock API - Plot Options Reference. Those whose value is not a function are generally available.

Examples

Plot two SMA values overlaying the price chart.

plot("SMA", sma(5), sma(30));

Plot two SMA values overlaying the price chart as an area range.

plot("SMA", [sma(5), sma(30)]);

Plot two SMA values overlaying the price chart, the volume as bars overlaying the price chart but on it's own opposite y-axis and the raw stochastic oscillator a study below.

plot("Example Plot",
    sma(5),
    sma(30),
    {name: "Volume", type: "bar", opposite: true, value: volume()},
    {name: "Stochastic Oscillator", overlay: false, value: stochasticOscillator(14)[0]}
);

error error(message)

Throws an immediate fatal error causing the trading session to terminate. Convenience for throw new Error(message);

Parameters

message string
The error message to be logged.

TICK_COUNT number

The number of ticks since the session began, i.e. the number of times onTick has executed. Unavailable to indicators.



JavaScript Libraries

These 3rd party libraries provide useful utilities for performing common tasks. Let us know if there are any particular libraries you find useful and we'll get them included (more to come).

Underscore.js _

Provides a whole suite of helpers primarily for manipulating arrays and objects. Access via the _ identifier. Full documentation at underscorejs.org.



Math Methods

We've added a handful of methods to the Math object to facilitate common statistical functions.

average Math.average(x)

Returns the mean average. Aliases Math.mean().

Parameters

x array
An array of numbers.

count Math.count(x)

Returns the length of the passed array. Equivalent to x.length, though additionally checks array type.

Parameters

x array
An array of numbers.

highest Math.highest(x)

Returns the highest number in the array. Shorthand for Math.max.apply(null, x).

Parameters

x array
An array of numbers.

lowest Math.lowest(x)

Returns the lowest number in the array. Shorthand for Math.min.apply(null, x).

Parameters

x array
An array of numbers.

mean Math.mean(x)

Returns the mean average.

Parameters

x array
An array of numbers.

meanDeviation Math.meanDeviation(x)

Returns the mean deviation, i.e. the mean absolute distance from the mean.

Parameters

x array
An array of numbers.

sum Math.sum(x)

Returns the sum of the values of the supplied array.

Parameters

x array
An array of numbers.

standardDeviation Math.standardDeviation(x)

Returns the standard deviation, i.e. the square root of the variance.

Parameters

x array
An array of numbers.

sumSquares Math.sumSquares(x)

Returns the sum of the squares of the values of the supplied array.

Parameters

x array
An array of numbers.

variance Math.variance(x)

Returns the mean of the squares of the deviations from the mean.

Parameters

x array
An array of numbers.


Technical Indicators

Technical indicators are available to both your trading algorithms and for use inside indicators themselves.

By default, technical indicators operate on historical data for the default instrument your session is running on. To access their value, simply call them inside your algorithms, passing any parameters.

The following returns the Simple Moving Average of the previous 5 bars.

sma(5);

You can also call indicators from within other indicators, nesting them.

Note that when doing so, only the getBufferSize and getRunUpCount functions of the topmost parent will be respected. You must make sure then that your parent script loads enough historical data and sets enough run up to accomodate any descendent indicators.

See Writing Your Technical Indicators - Structure - getBufferSize.


Mutiple Timeframes and Instruments

You can also run indicators on data for other interval timeframes by running them as follows.

M15.sma(5);           // SMA of previous 5 15 minute bars
H1.sma(5);            // SMA of previous 3 hourly bars

An indicator and all of its children produce values for a single instrument at a single timeframe interval, so this is not available when nesting indicators.

Use the following format to produce indicator values for data of any non default instrument.

var EURUSD = INSTRUMENTS["EUR/USD:FXCM"];
EURUSD.sma(5);        // SMA of previous 5 EURUSD bars (default interval timeframe)
EURUSD.M15.sma(5);    // SMA of previous 5 EURUSD 15 minute bars
EURUSD.H1.sma(5);     // SMA of previous 3 EURUSD hourly bars

Your Custom Indicators your_key()

To use your own custom indicators just call the key you specified on the technical indicator edit screen as a function in the normal manner, passing in any arguments your indicator is expecting. The value returned will be the return value of your onIntervalClose function at the current interval. Any chart configuration will be stripped out, returning only the value property. You can find more info on this in Writing Your Technical Indicators - Return Values.


Accumulation Distribution Line adl()

A momentum indicator whose value represents the cumulative flow of money into and out of a security by taking into account the price and volume, thus indicating buying or selling pressure. Where the line is consistent with the direction of an underlying trend the indicator can be used to substantiate the trend's sustainability.

Parameters

none

Returns

value number

Aroon aroon(periods)

The Aroon indicator determines the presence and strength of a price trend. The indicator produces two separate values, Aroon Up and Aroon Down, representing how far though the previous n periods we got before the highest high and lowest low were recorded (as a percent). Aroon Up being over 50 and Aroon Down being below 50 indicates a bullish trend.

Parameters

periods number
The number of periods for the indicator to act on.

Returns

value array [aroonUp, aroonDown]
aroonUp number
The Aroon Up value.
aroonDown number
The Aroon Down value.

Aroon Oscillator aroonOscillator(periods)

Returns the difference between the Aroon Up and Aroon Down values produced by the Aroon indicator. Ranges therefore between -100 and 100. Consistently positive values indicate a strong uptrend, while negative indicates downtrend.

Parameters

periods number
The number of periods for the indicator to act on.

Returns

value number

Average True Range atr(periods)

The Average True Range measures volatility by taking whichever is greatest of the high-low range, or distances between high and low and previous close and smoothing over n periods.

Parameters

periods number
The number of periods to incorporate in smoothing the true range.

Returns

value number

Bollinger Bands bollinger(periods, deviations)

A volatility indicator that draws bands either side of a moving average based on a multiple of the standard deviation of the previous n period closes. A tightening of the bands can indicate that volatility is about to increase rapidly.

Parameters

periods number
The number of periods on which to calculate the moving average and standard deviation. Typically 20.
deviations number
The multiplier to apply to the standard deviation. Typically 2.

Returns

value array [lowerBand, upperBand, SMA]
lowerBand number
The value of the lower band
upperBand number
The value of the upper band
SMA number
The Simple Moving Average mid line.

Bollinger Bandwidth bollingerBandwidth(periods, deviations)

The Bollinger Bandwidth study normalizes the width of Bollinger Bands by dividing it by the mid value.

Parameters

periods number
The number of periods on which to calculate the moving average and standard deviation. Typically 20.
deviations number
The multiplier to apply to the standard deviation. Typically 2.

Returns

value number

Bollinger %B bollingerB(periods, deviations)

The Bollinger %B indicator normalizes Bollinger Bands, representing the price in relation to the bands and can indicator overbought or oversold markets. A value of 0.5 means the price is at the SMA midline. A value greater than 1 means price is above the upper band and below 0 means price is lower than the lower band.

Parameters

periods number
The number of periods on which to calculate the moving average and standard deviation. Typically 20.
deviations number
The multiplier to apply to the standard deviation. Typically 2.

Returns

value number

Commodity Channel Index cci(periods, constant)

The Commodity Channel Index (CCI) is a momentum oscillator designed to help identify reversals and extremes of price and trend strength. Readings above 100 indicate that the market is overbought while readings below -100 indicate oversold.

Parameters

periods number
The number of periods to consider. Typically 20.
constant number
The multiplier to apply to the mean deviation denominator. Typically 0.15 as this ensures around 75% of values will fall inside the -100 to 100 range.

Returns

value number

Chandelier Exit chandelierExit(periods, multiplier)

Overlays a trailing a stop loss based on the distance of an Average True Range value from the n periods high or low (depending on the direction of the trade you are determining an exit for). It is designed to prevent premature exits while still in a trend.

Parameters

periods number
The number of periods to consider.
multiplier number
The multiplier to apply to the Average True Range value. Typically 3.

Returns

value array [shortStopLoss, longStopLoss]
shortStopLoss number
The indicated price at which to buy back failing short positions.
longStopLoss number
The indicated price at which to sell failing long positions.

Chaikin Money Flow cmf(periods)

Takes price accumulation/distribution and volume into consideration to determine the Money Flow Volume of n periods. A positive reading indicates buying pressure is stronger than selling pressure and vice versa.

Parameters

periods number
The number of periods to consider.

Returns

value number

Chande Momentum Oscillator cmo(periods, signalPeriods)

Measures momentum by taking into account sum of up and down price changes over n periods. Oscillates between -100 and 100. Reading above and below 50 and -50 are considered overbought and oversold. An EMA signal line is also returned to generate signals where it crosses the CMO.

Parameters

periods number
The number of periods to consider.
signalPeriods number
The number of periods to smooth to generate EMA signal line. Typically 9.

Returns

value array [cmo, cmoSignal]
cmo number
The indicator value.
cmoSignal number
The indicator smoothed by Exponential Moving Average.

Center of Gravity Oscillator cog(periods, signalPeriods)

The Center of Gravity Oscillator is a smoothed oscillator with zero lag identifying turning points by imagining previous n days as weights on a balanced beam. The indicator's EMA signal is also returned.

Parameters

periods number
The number of periods to consider. Typically 10.
signalPeriods number
The number of periods to smooth to generate EMA signal line. Typically 9.

Returns

value array [cog, cogSignal]
cog number
The indicator value.
cmoSignal number
The indicator smoothed by Exponential Moving Average.

Coppock Curve coppock(firstRoCPeriods, wmaPeriods, secondRoCPeriods)

Originally designed for stocks, this long term momentum indicator generates buy signals when below zero and retracing upwards. It takes into account two Rate of Change values, one smoothed with a Weighted Moving Average.

Parameters

firstRoCPeriods number
The number of periods from which to calculate the first Rate of Change. Typically 14.
wmaPeriods number
The number of first Rate of Change values to apply a Weighted Moving Average to. Typically 10.
secondRoCPeriods number
The number of periods from which to calculate the second Rate of Change. Typically 11.

Returns

value number

Detrended Price Oscillator dpo(periods)

Attempts to remove price trend from the equation by displacing its current value backwards to the middle of the look back period. The value itself is the offset from the Simple Moving Average. Note that though when drawn on charts this indicator has no value until the displacement periods have passed, the value returned for use in your algorithm does not account for this displacement.

Parameters

periods number
The number of periods to consider. Typically 20.

Returns

value array [dpo, sma]
dpo number
The indicator value (as if not displaced).
sma number
The price Simple Moving Average.

Elder Bull/Bear Power elderBBPower(periods)

Also known as the Elder-Ray Index, this indicator produces two values that determine the amount of buying and selling pressure, or "Bull Power" and "Bear Power". These are calculated from the current high and low less the Exponential Moving Average.

Parameters

periods number
The number of periods to consider. Typically 20.

Returns

value array [bullPower, bearPower]
bullPower number
A value representing buying pressure.
bearPower number
A value representing selling pressure.

Exponential Moving Average ema(periods)

Similar to the Simple Moving Average, this provides an smoothed curve overlaying the price, though gives more weight to recent data. The purpose of moving averages is to eliminate random short term price fluctuations, or noise.

Parameters

periods number
The number of periods to consider.

Returns

value number

Exponential Moving Average EnvelopeemaEnvelope(periods, envelope)

Plots parallel bands at a percent deviation either side of the Exponential Moving Average. Envelope value should be set for any given volatility so that price generally stays within the envelope such that departures identify particular strength or weakness in the market.

Parameters

periods number
The number of periods to consider.
envelope number
The percentage away from the Exponential Moving Average.

Returns

value array [[lowerBand, upperBand], EMA]
lowerBand number
The value of the lower band
upperBand number
The value of the upper band
EMA number
The Exponential Moving Average mid line.

Ease of Movement emv(periods)

Oscillates around zero providing a measure of how easily the market is moving, i.e. how much it can be moved with little volume. High values indicate buying pressure while low values indicate selling pressure.

Parameters

periods number
The number of periods to consider.

Returns

value number

Fisher Transform fisherTransform(periods)

This indicator helps to identify price reversals by providing sharp turning points. The Fisher Line crossing above or below its signal line can signal an opportunity to buy or sell.

Parameters

periods number
The number of periods to consider.

Returns

value array [value, signal]
value number
The indicator value.
signal number
The previous indicator value, considered a signal line.

Force Index forceIndex(periods)

Uses price change, extent and volume to determine the power behind a move, or buying and selling pressure. Can be used to identify or reinforce a trend. The value is smooth by Exponential Moving Average to produce a value.

Parameters

periods number
The number of EMA periods to smooth the value.

Returns

value number

Gopalakrishnan Range Index gapo(periods)

The Gopalakrishnan Range Index (GAPO) quantifies a price's variability, identifying whether a market is consistent or erratic. The log of the difference between highest high and lowest low is divided by the log of the periods. A higher value indicates a chaotic market.

Parameters

periods number
The number of periods to consider.

Returns

value number

Ichimoku Cloud ichimokuCloud(conversionLinePeriods, baseLinePeriods, leadingSpanPeriods, laggingSpanPeriods)

Ichimoku Cloud overlays indicate levels of support and resistance, price momentum and trend directions and provide signals to buy or sell. Note that the lagging span and leading span lines that form the cloud are offset when drawn onto charts. When used inside your algorithms this offset is disregarded.

Parameters

conversionLinePeriods number
The number of periods from which to calculate the Tenkan-sen (conversion) line.
baseLinePeriods number
The number of periods from which to calculate the Kijun-sen (base) line.
leadingSpanPeriods number
The number of periods from which to calculate the Senkou (leading) B line.
laggingSpanPeriods number
The number of periods to displace Chikou (lagging) line when plotted on charts (does not affect return value).
value array [conversionLine, baseLine, leadingSpanA, leadingSpanB, laggingSpan]
conversionLine number
The Tenkan-sen line is the average of the `conversionLinePeriods` high and low.
baseLine number
The Kijun-sen line is the average of the `baseLinePeriods` high and low.
leadingSpanA number
The Senkou Span A line is the average of the previous two and forms the faster cloud line.
leadingSpanA number
The Senkou Span A line is the average of the `leadingSpanPeriods` high and low and forms the slower cloud line.
laggingSpan number
The lagging span is simply the close price. On charts this is displaced `laggingSpanPeriods` in the past.

Keltner Channels keltnerChannels(emaPeriods, atrPeriods, atrMultiplier)

Keltner bands set an envelope either side of an Exponential Moving Average. The channel width depends on volatility as measured according to the Average True Range. As trend following indicator, bar closes above the upper line indicate a strong bullish market and vice versa.

Parameters

emaPeriods number
The number of periods from which to draw an Exponential Moving Average.
atrPeriods number
The number of periods from which to determine the Average True Range.
atrMultiplier number
The multiplier to apply to the ATR. Typically 2.

Returns

value array [[lowerBand, upperBand], EMA]
lowerBand number
The value of the lower band
upperBand number
The value of the upper band
SMA number
The Exponential Moving Average mid line.

Know Sure Thing kst(firstROCPeriods, secondROCPeriods, thirdROCPeriods, fourthROCPeriods, firstSMAPeriods, secondSMAPeriods, thirdSMAPeriods, fourthSMAPeriods[, signalSMA])

Know Sure Thing is a momentum oscillator that takes Simple Moving Averages of the Rate of Change of four look back periods and sums the result with a weighting towards the longest (fourth) period. If a value is provided for signalSMA, a Simple Moving Average signal line is also returned. The KST reading crossing above its 9 day moving average is considered a buy signal, and vice versa.

Parameters

firstROCPeriods number
The number of periods to calculate the first Rate of Change over. Suggest 10.
secondROCPeriods number
The number of periods to calculate the second Rate of Change over. Suggest 15.
thirdROCPeriods number
The number of periods to calculate the third Rate of Change over. Suggest 20.
fourthROCPeriods number
The number of periods to calculate the fourth Rate of Change over. Suggest 30.
firstSMAPeriods number
The number of first Rate of Change values from which to take a Simple Moving Average. Suggest 10.
secondSMAPeriods number
The number of second Rate of Change values from which to take a Simple Moving Average. Suggest 10.
thirdSMAPeriods number
The number of third Rate of Change values from which to take a Simple Moving Average. Suggest 10.
fourthSMAPeriods number
The number of fourth Rate of Change values from which to take a Simple Moving Average. Suggest 15.
signalSMA number
Optional. If provided, produces a signal line which is a Simple Moving Average of the indicator reading. Suggest 9.

Returns

value number
The indicator reading.
or value array [kst, signal]
An array is returned if a value is provided for `signalSMA`.
kst number
The indicator reading.
signal number
The Simple Moving Average of the indicator reading.

MACD macd(fastEMAPeriods, slowEMAPeriods[, signalEMAPeriods])

The MACD, or moving average convergence/divergence, indicator charts momentum by calculating the difference between a fast and slow Exponential Moving Average of the previous closes. Also returned, where signalEMAPeriods is provided, are an EMA smoothed signal line and a third value which is the difference of the two. Signal line crossovers can indicate trade opportunities (crossing above to buy and vice versa).

Parameters

fastEMAPeriods number
The number of periods to take the fast Exponential Moving Average of. Suggest 12.
slowEMAPeriods number
The number of periods to take the slow Exponential Moving Average of. Suggest 26.
signalEMAPeriods number
Optional. The number of MACD readings to take Exponential Moving Average of for the signal line. Suggest 9.

Returns

value number
The indicator reading.
or value array [macd, signal, histogram]
An array is returned if a value is provided for `signalEMAPeriods`.
macd number
The indicator reading.
signal number
The Exponential Moving Average of the indicator reading.
histogram number
Technically not a histogram, the difference between the macd and signal.

MACD Histogram macdHistogram(fastEMAPeriods, slowEMAPeriods, signalEMAPeriods)

The difference between the fast and slow EMA readings of the MACD indicator, described above.

Parameters

fastEMAPeriods number
The number of periods to take the fast Exponential Moving Average of. Suggest 12.
slowEMAPeriods number
The number of periods to take the slow Exponential Moving Average of. Suggest 26.
signalEMAPeriods number
The number of MACD readings to take Exponential Moving Average of for the signal line. Suggest 9.

Returns

value number
The indicator reading.

Mass Index macdHistogram(emaPeriods, summationPeriods)

A directionless volatility indicator that uses widening of price range to predict trend reversals. Sums the ratio between an EMA and a double EMA (smoothed twice) over summationPeriods days.

Parameters

emaPeriods number
The number of differentials to take the Exponential Moving Averages of. Suggest 9.
summationPeriods number
The number of EMA ration to take summation of. Suggest 25.

Returns

value number
The indicator reading.

Money Flow Index mfi(periods)

The Money Flow Index oscillator measure the strength of a trend by incorporating volume into the Relative Strength Index (RSI) indicator. Ranging between 0 and 100, readings above 80 or below 20 are considered to indicate an overbought or oversold market respectively.

Parameters

periods number
The number of differentials to take the Exponential Moving Averages of. Suggest 9.

Returns

value number
The indicator reading.

On Balance Volume obv()

On Balance Volume (OBV) is a cumulative momentum oscillator that adds volume where a bar closes higher than previously and subtracts it where it closes lower. It works on the basis that large volume increases in either direction forecast price movement in that direction.

Returns

value number
The indicator reading.

Percentage Price Oscillator ppo(fastEMAPeriods, slowEMAPeriods[, signalEMAPeriods])

Related to the MACD, the Percentage Price Oscillator (PPO) measures momentum by representing the difference between two Exponential Moving Averages as a percent of the slower moving average. Where signalEMAPeriods is supplied, an EMA of the reading and the difference between the two is also returned. Unlike the MACD, this indicator is normalized as a percentage so can be compared to other instruments.

Parameters

fastEMAPeriods number
The number of periods for fast EMA price smoothing.
slowEMAPeriods number
The number of periods for slow EMA price smoothing.
signalEMAPeriods number
Optional. If provided, will also return an EMA of the indicator reading.

Returns

value number
The indicator reading.
or value array [ppo, signal, histogram]
An array is returned if a value is provided for `signalEMAPeriods`.
pmo number
The indicator reading.
signal number
The Exponential Moving Average of the indicator reading.
histogram number
The difference between the above.

Pretty Good Oscillator pgo(periods)

The Pretty Good Oscillator (PGO) is the difference between the current close and the Simple Moving Average of look back periods closes, expressed in terms of the Average True Range of the same period. Oscillating around zero, the suggestion is that a reading above 3 is a buy signal for a longer term trend, while below 3 is a sell signal. In either case exit when the value returns to zero (i.e. close is equal to SMA).

Parameters

periods number
The SMA and ATR periods. Typically 14.

Returns

value number
The indicator reading.

Price Channels priceChannels(periods)

The Price Channels overlay returns the highest high and lowest low for the periods specified. Price moving outside these bands show a new high or low, indicating overbought or oversold levels.

Parameters

periods number
The number of look back periods. Typically 20.

Returns

value array [[lowerChannel, upperChannel], midLine]
lowerChannel number
The lowest low for the `periods`.
upperChannel number
The highest high for the `periods`.
midLine number
The mid line of the two.

Price Momentum Oscillator pmo(firstEMAPeriods, secondEMAPeriods[, signalEMAPeriods])

The Price Momentum Oscillator (PMO) takes the Rate of Change and double smooths it with Exponential Moving Averages. The output is normalized such that it can be used to compare various instruments in ranking relative strength. Steeper readings indicate more pressure behind a price move.

Parameters

firstEMAPeriods number
The number of Rate of Change periods for first EMA smoothing.
secondEMAPeriods number
The number of Rate of Change periods for second EMA smoothing.
signalEMAPeriods number
Optional. If provided, will return an EMA of the indicator reading.

Returns

value number
The indicator reading.
or value array [pmo, signal]
An array is returned if a value is provided for `signalEMAPeriods`.
pmo number
The indicator reading.
signal number
The Exponential Moving Average of the indicator reading.

Price Volume Oscillator pvo(fastEMAPeriods, slowEMAPeriods, signalEMAPeriods)

The Percentage Volume Oscillator (PVO) provides a oscillator reading for volume. It is expressed as the difference between two EMAs of interval volumes as a percentage of the longer EMA. If a signalEMAPeriods is supplied, it also returns a signal line which is the EMA of the reading and the difference between the two.

Parameters

fastEMAPeriods number
The number of periods for fast EMA volume smoothing.
slowEMAPeriods number
The number of periods for slow EMA volume smoothing.
signalEMAPeriods number
Optional. If provided, will also return an EMA of the indicator reading.

Returns

value number
The indicator reading.
or value array [pvo, signal, histogram]
An array is returned if a value is provided for `signalEMAPeriods`.
pvo number
The indicator reading.
signal number
The Exponential Moving Average of the indicator reading.
histogram number
The difference between the above.

QStick qStick(periods)

The QStick indicator take the periods Simple Moving Average over the open - close differences. Positive readings indicate a bullish bias, while negative reading indicate bearish.

Parameters

periods number
The number of periods to smooth the price movements over.

Returns

value number
The indicator reading.

Rate of Change roc(periods)

The Rate of Change (ROC) is the pure momentum of price movement. It is simply the percentage change in price since N periods ago. Oscillating around zero, prices are bullish

Parameters

periods number
The number of periods to smooth the price movements over.

Returns

value number

Relative Strength Index rsi(periods)

The Relative Strength Index (RSI) is a popular momentum oscillator that measures the speed and magnitude of recent gains in comparison to recent losses. Ranging between 0 and 100, readings above 70 are considered overbought, while below 30 oversold.

Parameters

periods number
The number of look back periods.

Returns

value number
The indicator reading.

Simple Moving Average sma(periods)

Returns the Simple Moving Average value for the look back period specified by periods. A Simple Moving Average is the average of the close prices for the last n interval periods. A shorter period gives a "faster" SMA, which will trace the price more closely. Inversely, a longer period will be slower to react to price movement. Deviations from moving averages are often used to signal entry or exit conditions. Up or down trends can be signalled by the crossing of slower and faster moving averages.

Parameters

periods number
The number of periods to calculate the average close price from.

Returns

value number

Example

Compare fast and slow SMAs to determine the direction of a trend.

if (sma(5) > sma(30)) {
    bullish = true;
} else {
    bullish = false;
}

Simple Moving Average Envelope smaEnvelope(periods, envelope)

Plots parallel bands at a percent deviation either side of the Exponential Moving Average. Envelope value should be set so that price generally stays within the envelope such that departures identify particular strength or weakness in the market.

Parameters

periods number
The number of periods to consider.
envelope number
The percentage away from the Simple Moving Average.

Returns

value array [[lowerBand, upperBand], SMA]
lowerBand number
The value of the lower band.
upperBand number
The value of the upper band.
SMA number
The Simple Moving Average mid line.

Standard Deviation standardDeviation(periods, envelope)

The Standard Deviation is a direct statistical measure of an instrument's volatility, i.e. variability or deviation away from the average. Determining the volatility of an underlying price can help in determining where to set envelopes that indicate overbought or oversold conditions.

Parameters

periods number
The number of period closes to calculate the standard deviation of.

Returns

value number
The indicator reading.

Stochastic Oscillator stochasticOscillator(periods, smaPeriods)

The Stochastic Oscillator is a momentum indicator that compares the current price to the look back period high - low range. By doing so, it aims to predict price reversal points on the basis that changes in the direction of momentum generally precede price. Typically readings above 80 indicate overbought and below 20 indicate oversold.

Parameters

periods number
The number of look back periods. Typically 14.
smaPeriods number
The number readings from which to produce a SMA signal line. Typically 3.

Returns

value array [stochasticOscillator, signal]
stochasticOscillator number
The indicator reading.
signal number
The signal line.

StochRSI stochRsi(periods)

The StochRSI applies the Stochastic Oscillator to the period Relative Strength Index values rather than price directly. The offers increased sensitivity that the RSI, particularly when RSI readings stay within their threshold levels, therefore generating signals more frequently. Ranging between 0 and 1, values above 0.8 indicate an overbought marker, while below 0.2 indicate oversold. Readings consistently above 0.5 suggest an uptrend, below 0.5, a downtrend.

Parameters

periods number
The number of look back periods. Typically 14.

Returns

value number
The indicator reading.

TRIX trix(periods[, signalPeriods])

The TRIX momentum oscillator triple EMA smooths the close prices for the last n periods and produces a value that is the percent change since the last triple smoothed value, or rate of change. By doing so it effectively filters out any random short term noise. If a value for signalPeriods is provided it will also output a signal line which is an EMA of the TRIX values. Crosses above and below the signal line can be considered trade signals (above being bullish, and vice versa).

Parameters

periods number
The number of look back periods. Typically 15.
signalPeriods number
Optional. The number of indicator readings to smooth with an EMA. Typically 9.

Returns

value number
The indicator reading.
or value array [trix, signal]
An array is returned if a value is provided for `signalPeriods`.
trix number
The indicator reading.
signal number
The Exponential Moving Average of the indicator reading.

True Strength Index tsi(firstPeriods, secondPeriods[, signalPeriods])

The True Strength Index (TSI) combines momentum and double EMA smoothed close prices to offer and indication of overbought and oversold situations. Oscillating around zero, positive values indicate a bullish bias, while readings below zero indicate bearish sentiment. If signalPeriods is supplied, an EMA signal line is also generated. Crosses above and below the signal can indicate trend reversals. Output fluctuates between -100 and 100. Readings above 25 and below -25 can be interpreted as overbought and oversold levels.

Parameters

firstPeriods number
The number of close periods to smooth with a Simple Moving Average. Typically 25.
secondPeriods number
The number of first SMA values to smooth again. Typically 13.
signalPeriods number
Optional. The number of readings to smooth with an EMA. Typically 9.

Returns

value number
The indicator reading.
or value array [trix, signal]
An array is returned if a value is provided for `signalPeriods`.
trix number
The indicator reading.
signal number
The Exponential Moving Average of the indicator reading.

Ultimate Oscillator uo(shortPeriods, mediumPeriods, longPeriods)

The Ultimate Oscillator momentum indicator incorporates the averages of three separate time periods, applying weighting towards the shortest. By doing so it filters out short term fluctuations that could be misinterpreted as signals. Buying pressures values are measured against true range values and the weighted average taken to produce a reading in the range 0 to 100. Values below 30 indicate oversold, while those above 70 indicate overbought. Signals are generated from moves across these while diverging from the underlying price.

Parameters

shortPeriods number
The number of periods for the first calculation. Typically 7.
mediumPeriods number
The number of periods for the second calculation. Typically 14.
longPeriods number
The number of periods for the third calculation. Typically 28.

Returns

value number
The indicator reading.

Volume volume()

The Volume is simply the number of ticks received during the interval. Note that where instruments are not traded over a central exchange (e.g. Forex, CFDs), the real volume sizes of trades cannot be determined. The volume, or tick count, is therefore only a loose indicator of overall trading activity in the market and is determined ultimately by the retail broker. Though the playing field remains level, this should be taken into consideration for all indicators that derive a value from volume.

Returns

value number
The indicator reading.

Vortex Indicator vtx(periods)

The Vortext Oscillator returns two oscillator values indicative of positive and negative trend movement. These are expressed in relation to the True Range. The positive indicator reading crossing above the negative reading is considered a bullish signal and vice versa. These signals are strengthened by crosses preceding breaches of key levels, considered to be 0.9 and 1.1, i.e. a buy signal is only realized after a cross and once the negative indicator crosses below 0.9, and vice versa.

Parameters

periods number
The number of look back periods.

Returns

value array [vi-, vi+]
vi- number
The negative reading.
vi+ number
The positive reading.

Williams %R williamsR(periods)

The Williams %R momentum oscillator produces the same results as the Stochastic Oscillator, though on a different scale. Close prices are calculated in terms of the highest high for the period, an inversion of the Stochastic Oscillator, then inverted back by multiplying by -100. Rangind between 0 and -100, readings above -20 indicate overbought, while below -80 indicate oversold.

Parameters

periods number
The number of look back periods.

Returns

value number
The indicator reading.

Weighted Moving Average wma(periods)

Like the Exponential Moving Average, the Weighted Moving Average overlay draws a smoothing curve that applies weighting to recent close prices. The weighting however falls off linearly. The close prices are multiplied by their position in the series, summed and then divided by the sum of the multipliers.

Parameters

periods number
The number of period closes to average.

Returns

value number
The indicator reading.

Was this page useful? If you find any errors or have any questions please get in touch at support@cloud9trader.com.