Trade Smarter with Automation

Using the $data API

The $data API provides access to stock quotes, charts, option chains, spreads and other data useful for trading. $data is available in the Alta5 console and async bot events.

Execute a query

$data API functions initiate a data query and the then() function executes the query and waits for the results. The result of the query is passed as an argument to the supplied callback function:

$data.security('JPM').then(function(jpm){
    // The "jpm" variable is a Security object with
    // real-time quote values and other analytics
});

Query options

A $data query consists of a JavaScript object with option:value pairs. The options available for each type of query are listed in the API reference.

var query = {
    symbol: 'JPM',
    interval: '1m',
    period: 'intraday'
};
$data.chart(query).then(function(chart){
    // chart is ready to analyze
});

Dates

A query can specify dates in one of the the following formats:

  • JavaScript Date
  • String in the format YYYY-MM-DD
  • Relative dates in english, e.g. 'yesterday', '3 days ago', 'last friday'.
var query = {
    symbol: 'JPM',
    interval: '1d',
    start: new Date(2017, 1, 16),   // <-- Date object
    end: 'yesterday'   // <-- relative date
};

Multiple queries

The $data API automatically batches multiple queries. It passes all data results as arguments (in order) to the supplied callback function:

$data.security('JPM')
    .snapshot('VIX', 'yesterday')
    .chart({
        symbol: 'DAL',
        interval: '1d',
        period: '30d'
    })
    .then(function(jpm, vix, chart){
        // all data is ready to analyze
    });

Some $data functions also accept an array of queries to request an array of results:

var queries = [{
    symbol: 'DAL',
    date: 'yesterday'
},{
    symbol: 'DAL',
    date: 'last friday'
}];

$data.snapshot(queries).then(function(snaps){
    var yesterday = snaps[0],
        friday = snaps[1];
});

Inspect results in the Console

You can explore the $data API and the structure of returned data in the Alta5 Console with the $log function.

For example, this query:

$data.snapshot('JPM', 'last friday').then($log);

Returns this data:


$data in event scripts

The $data API is available in async bot event scripts, including wake, the first event fired each day the market is open. Your code must signal the bot that it has finished loading data by invoking the $done function. Since the $data API is asynchronous, $done will generally be invoked in the then() callback:

$data.snapshot('VIX', 'yesterday')
    .then(function(vix){
        $vix = vix; //  <-- define $vix
        $done();   //   <-- call $done
    });

Failing to invoke $done in your event code will cause your bot to get stuck with a "loading" status.


Import results as a bot variable

Each individual query can have an id property to have the results of that query defined as a bot variable. Bot variables can then be accessed in any other event scripts, e.g. scan, after loading has completed.

var query = {
    id: 'spread', // <-- defines "$spread" variable
    type: 'bearcall',
    symbol: 'DAL',
    days: 14,
    legs: [50, 51]
};
$data.spreads(query).then($done);

The code above produces a variable, $spread, that has computed properties and real-time pricing information for analysis. For example, a scan event using $spread:

if($stock.last > $signal && $spread.returnRate > $returnRate){
    $bot.open({
        type: 'bearcall',
        spread: $spread,
        memo: 'Bounce above signal: ' + $signal + ' to: ' + $stock.last
    });
}

API Reference

balances(query) Array

Returns an account object with properties containing balances for accountId.

Query options
  • String

    The Alta5 account id (defaults to the bot's accountId or 'sim' for paper trading).

  • String

    Import as a bot variable. More...

Usage
$data.balances({accountId: 'sim'}).then($log);

Logs:

chart(query) Chart

Returns a historical or intraday chart with technical indicators.

Query options
  • String

    Stock ticker symbol. (e.g. 'AAPL' for Apple)

  • String

    The aggregation interval for bars in the chart. Intervals 5m and lower are available for the last 20 market days. Intraday charts can have up to a 30m interval.

    Intraday:
    1m, 2m, 3m, 4m, 5m, 10m, 15m, 20m, 30m
    Historical:
    1m, 2m, 3m, 4m, 5m, 10m, 15m, 20m, 30m, 1h, 2h, 3h, 4h, 8h, 12h, 1d, 2d, 3d, 4d, 1w

  • String

    The duration of the chart. For example, a chart with a period of '30d' would contain the 30 days of bars with the last bar being the end date. period is optional (and ignored) if both start and end are provided.

    Supported periods:
    intraday, 1d, 2d, 3d, 4d, 5d, 10d, 15d, 20d, 30d, 90d, 180d, 1mo, 3mo, 6mo, 9mo, 1y, 2y, 3y, 5y, 10y

  • String/Date

    The date of the first bar in the chart. Optional if a period is provided. Date formats...

  • String/Date

    The date of the last bar in the chart. Defaults to 'yesterday'. Optional if a period is provided. Date formats...

  • String

    Import as a bot variable. More...

  • Number/Boolean

    Keeps intraday charts in a loading state until there are at least minBars bars in the chart. Set to true to use the longest indicator time period (chart.indicatorMinBars).
    Useful if the chart uses an indicator with a timePeriod option. e.g. minBars: 12 would keep a bot in "loading" status and prevent scanning routines from being triggered until the chart has at least 12 bars.

  • Array

    Optional array with indicator options. More about indicators...

Usage
// Intraday chart with 1 min bars
var query = {
    id: 'chart',   // <-- define $chart variable
    symbol: 'JPM',
    interval: '1m',
    period: 'intraday'
};
$data.chart(query).then($done);
// 10 days preceding last friday, 1 day bars
var query = {
    id: 'chart',
    symbol: 'JPM',
    interval: '1d',
    period: '10d',
    end: 'last friday'
};
$data.chart(query).then($done);
// Last 30 days, 1 day bars, RSI indicator
var query = {
    symbol: 'JPM',
    interval: '1d',
    period: '30d',
    minBars: true,  // stays loading until there are 14 bars for the RSI indicator
    indicators: [{
        type: 'rsi',
        timePeriod: 14
    }]
};

$data.chart(query).then(function(chart){
    // chart is ready to analyze, e.g.
    var rsi = chart.lastBar.indicator('rsi');
    ...
});

estimize(query) Array

Returns an array containing earning report dates, estimates and results for symbol.

Query options
  • String

    Stock ticker symbol. (e.g. 'AAPL' for Apple)

  • String/Date

    Filter to only include reports on or after from date. Date formats...

  • String/Date

    Filter to only include reports on or before to date. Date formats...

  • String

    Import as a bot variable. More...

Usage
var query = {
    id: 'reports',   // <-- define $reports
    symbol: 'DAL',
    from: '3 years ago',
    to: 'today'    // <-- filter unreported future dates
};
$data.estimize(query).then($log);

Logs:

http(opts) data

Fetch data at url over HTTP/HTTPS.

Options
  • String

    A valid URL.

  • String

    For get requests, data is appended to url as a query string. For post requests, data is posted to url encoded using encoder.

  • String

    An object containing any HTTP headers to send, e.g. {sessionId: 'ABC123456'}.

  • String

    The type of encoding to use for posting data. Use 'url' for standard form encoding or 'json' to post as JSON.

  • String

    The type of HTTP request, 'get' or 'post'.

  • String

    Specifies how to parse the response. Use 'json' for JSON data or 'csv' for csv files.

  • String

    Used with password to perform standard HTTP authentication.

  • String

    Used with username to perform standard HTTP authentication.

Usage
// pull AAPL short interest
var req = {
    url: 'http://download.finance.yahoo.com/d/quotes?s=AAPL&f=sns7&e=.csv',
    parser: 'csv'
};
$data.http(req).then($log);

option(query) Security

Returns one or more Security objects for stock or index options.

query can be a standard query object or an array of query objects.

Query options
  • String

    Stock ticker symbol for the underlying option chain. (e.g. 'SPX' for S&P 500)

  • String

    The type of option. ('call' or 'put')

  • Number/Array

    The strike price of the option or an array containing a range of strike prices. (e.g. [50, 55] would return all options with a strike price between 50 and 55). All queries must have either strike or delta.

  • Number/Array

    The delta of the option (matches nearest) or an array containing a delta range. (e.g. [.3, .5] would return all options with a delta between .3 and .5). All queries must have either strike or delta.

  • Number

    Query from the first option series with at least days to expiration. Optional if a expiration is provided.

  • String/Date

    Query from the first option series that expires on or after the expiration date. Optional if a days is provided. Date formats...

  • String

    Filter option series by expiration style. Valid values are *, weeklys, monthlys, eom, standard, quarterlys. Defaults to *. Use a comma separated list to include more than 1 (e.g. 'weeklys,quarterlys').

  • String

    Filter option series by settlement style. Valid values are *, open, close. Defaults to *.

  • Boolean

    true to only query standard monthly series that expire on the 3rd friday of each month.

  • String

    Import as a bot variable. More...

Usage
var query = {
    symbol: 'AAPL',
    type: 'put',
    expiration: 'next friday',  // <-- relative date
    strike: 123
};

$data.option(query).then(function(put){
    var theta = put.theta;  // <-- real-time value
    ...
});
var query = {
    symbol: 'AAPL',
    type: 'put',
    expiration: 'next friday',
    strike: [135, 140]  // <-- all puts between 135 - 140
};

$data.option(query).then(function(puts){
    // puts is an array
    ...
});
var query = {
    symbol: 'DAL',
    type: 'call',
    days: 30,
    delta: [.2, .4]  // <-- all calls with delta between .2 - .4
};

$data.option(query).then(function(calls){
    // puts is an array
    ...
});
// multi query as an array
var multi = [{
    symbol: 'AAPL',
    type: 'call',
    days: 10,   // <-- at least 10 days to exp
    strike: 125
},{
    symbol: 'AAPL',
    type: 'call',
    days: 10,
    strike: 126
}];

$data.option(multi).then(function(options){
    var shortLeg = options[0],
        longLeg = options[1];
    ...
});
// multi query with bot variables
var multi = [{
    id: 'shortLeg',   // <-- define $shortLeg variable
    symbol: 'AAPL',
    type: 'call',
    days: 10,
    strike: 125
},{
    id: 'longLeg',   // <-- define $longLeg variable
    symbol: 'AAPL',
    type: 'call',
    days: 10,
    strike: 126
}];
$data.option(multi).then($done);

optionchain(query) OptionChain

Returns an OptionChain object with one or more series of stock or index options.

Query options
  • String

    Stock ticker symbol for the option chain. (e.g. 'SPX' for S&P 500)

  • Number

    The minimum number of days to expiration for the first option series.

  • String

    Import as a bot variable. More...

  • Number

    The maximum strike price for options in the chain.

  • Number

    The minimum strike price for options in the chain.

  • String

    Only include series from a specific month in the format YYYYMM. Can be comma separated list of months.

  • Boolean

    true to only include standard monthly series that expire on the 3rd friday of each month.

  • String

    Filter by traditional option ranges: near, in and out of the money. ('*', 'ntm', 'itm' or 'otm'; defaults to '*')

  • String

    Filter option series by expiration style. Valid values are *, weeklys, monthlys, eom, standard, quarterlys. Defaults to *. Use a comma separated list to include more than 1 (e.g. 'weeklys,quarterlys').

  • String

    Filter option series by settlement style. Valid values are *, open, close. Defaults to *.

  • Number

    The number of option series to include in the chain. (1 - 4; defaults to 1)

  • Number

    The number of strike prices to include in each option series. (1 - 50; defaults to 20)

  • String

    The type of options to include. ('*', 'call' or 'put'; defaults to '*')

Usage
// 2 series of puts, 12 strikes each
var query = {
    id: 'chain',   // <-- define $chain variable
    symbol: 'SPX',
    type: 'put',
    series: 2,
    strikes: 12,
    range: 'otm',  // <-- out the money
    days: 14       // <-- min 14 days to exp
};
$data.optionchain(query).then($done);

optionrange(query) OptionRange

Used to load and maintain a range of options by delta or theta.

Query options
  • String

    Stock ticker symbol for the underlying option chain. (e.g. 'SPX' for S&P 500)

  • String

    The type of option. ('call' or 'put')

  • String

    Either 'delta' or 'theta'.

  • Array

    The range of values to maintain. (e.g. [.3, .5])

  • Number

    Filter for the first option series with at least days to expiration. Optional if a expiration is provided.

  • String/Date

    Filter for the first option series that expires on or after the expiration date. Optional if a days is provided. Date formats...

  • String

    Filter option series by expiration style. Valid values are *, weeklys, monthlys, eom, standard, quarterlys. Defaults to *. Use a comma separated list to include more than 1 (e.g. 'weeklys,quarterlys').

  • String

    Filter option series by settlement style. Valid values are *, open, close. Defaults to *.

  • Boolean

    true to only query standard monthly series that expire on the 3rd friday of each month.

  • String

    Import as a bot variable. More...

Usage
var query = {
    id: 'calls',
    symbol: 'AAPL',
    type: 'call',
    days: 30,
    greek: 'delta',   // <-- tied to delta
    range: [.2, .4]   // <-- the range to maintain
};

$data.optionrange(query).then($done);

optionseries(query) OptionSeries

Used to lookup details about an option series and strike prices.

Query options
  • String

    Stock ticker symbol for the underlying option chain. (e.g. 'SPX' for S&P 500)

  • Number

    Filter for the first option series with at least days to expiration. Optional if a expiration is provided.

  • String/Date

    Filter for the first option series that expires on or after the expiration date. Optional if a days is provided. Date formats...

  • String

    Filter option series by expiration style. Valid values are *, weeklys, monthlys, eom, standard, quarterlys. Defaults to *. Use a comma separated list to include more than 1 (e.g. 'weeklys,quarterlys').

  • String

    Filter option series by settlement style. Valid values are *, open, close. Defaults to *.

  • Boolean

    true to only query standard monthly series that expire on the 3rd friday of each month.

  • String

    Import as a bot variable. More...

Usage
var query = {
    symbol: 'JPM',
    expiration: 'next friday'
};

$data.optionseries(query).then(function(series){
    // API functions
    var a = series.nearest(50);  // strike nearest $50
    var b = series.gt(50);       // greater than
    var c = series.gte(50);      // greater than / equal to
    var d = series.lt(50);       // less than
    var e = series.lte(50);      // less than / equal to

    var strikes = series.strikes;     // array of all strike prices

    series.forEach(function(price){

    });
});

positions(query) Array

Returns an array of the current positions held in accountId.

Query options
  • String

    The Alta5 account id (defaults to the bot's accountId or 'sim' for paper trading).

  • String

    Import as a bot variable. More...

Usage
$data.positions({accountId: 'sim'}).then($log);

Logs:

security(query) Security

Returns a Security object for an equity, index or ETF.

query can be a string with a ticker symbol or a standard query object.

Query options
  • String

    Stock ticker symbol. (e.g. 'AAPL' for Apple)

  • String

    Import as a bot variable. More...

Usage
// shorthand query
$data.security('JPM').then(function(jpm){
    var price = jpm.ask;   // <-- always the latest price
    ...
});
var query = {
    id: 'jpm', // <-- define $jpm variable
    symbol: 'JPM'
};
$data.security(query).then($done);

snapshot(query) Snapshot

Returns a snapshot quote for symbol on the specified date(s).

Query options
  • String

    Stock ticker symbol. (e.g. 'AAPL' for Apple)

  • String/Date/Array

    The date for the snapshot or an array of dates. Date formats...

  • String

    Import as a bot variable. More...

Usage
var query = {
    symbol: 'AAPL',
    date: 'last friday'
};
$data.snapshot(query).then(function(snap){
    var close = snap.close;
    ...
});
// multiple dates
var query = {
    symbol: 'AAPL',
    date: ['last monday', 'last friday']
};
$data.snapshot(query).then(function(snaps){
    var change = snaps[1].close - snaps[0].open;
    ...
});
// shorthand
$data.snapshot('JPM', 'yesterday').then(function(snap){
    ...
});
// chaining
$data.snapshot('AAPL', 'last friday')
    .snapshot('VIX', 'yesterday')
    .then(function(aapl, vix){
        ...
    });

spreads(query) Spread

Returns a Spread object with properties containing real-time market pricing and analytics (return rate, breakeven, risk/reward, etc).

Query options
  • String

    Stock ticker symbol for the option chain. (e.g. 'SPX' for S&P 500)

  • String

    The type of spread. 'bullput', 'bearcall' and 'ironcondor' are implemented. 'bullcall', 'bearput' and 'calendar' are next on the roadmap.

  • Array

    Array containing the strike prices for the spread, e.g. [105, 106]. Prices can be in any order.

  • Number

    Create spread from the first option series with at least days to expiration. Optional if a expiration is provided.

  • String/Date

    Create spread from the first option series that expires on or after the expiration date. Optional if a days is provided. Date formats...

  • Boolean

    true to only include options that expire on the 3rd friday of each month.

  • String

    Filter option series by expiration style. Valid values are *, weeklys, monthlys, eom, standard, quarterlys. Defaults to *. Use a comma separated list to include more than 1 (e.g. 'weeklys,quarterlys').

  • String

    Filter option series by settlement style. Valid values are *, open, close. Defaults to *.

Usage
var query = {
    id: 'bp',  // <-- define $bp variable
    symbol: 'AAPL',
    type: 'bullput',
    expiration: 'next friday',
    legs: [105, 106]
};
$data.spreads(query).then($done);

then(callback)

Executes any pending queries and passes the results to the supplied callback function (in order).

See Using $data for additional details.

Usage
// single
$data.security('JPM').then(function(jpm){
    // The "jpm" variable is a Security object with
    // real-time quote values and other analytics
});
// multi
$data.security('JPM')
    .snapshot('VIX', 'yesterday')
    .chart({
        symbol: 'DAL',
        interval: '1d',
        period: '30d'
    })
    .then(function(jpm, vix, chart){
        // all data is ready to analyze
    });
var query = {
    id: 'chart',        // <- defines $chart var
    symbol: 'JPM',
    interval: '1d',
    period: '10d',
    end: 'last friday'
};
$data.chart(query).then($done); // <-- $done called when $chart is loaded