Trade Smarter with Automation

Strategy Basics

This document is an introduction to trading strategies that run in the alta5 platform. It assumes the reader has basic programming skills.

Introduction

What is a Strategy?

A Strategy in Alta5 is a definition of the parameters, workers and instructions for making automated trades based on predefined market conditions.

The basic Strategy structure looks like this:


Strategy.define({
    name: 'My Test Strategy',
    description: 'This is only a test',

    // the type of position this strategy seeks/manages
    positionType: Position.EQUITY,

    // define parameters
    params: [...],

    // define workers
    workers: [...],

    // called when scanning for a new position
    onSeek: function(target, data){

        // your to code to find a winner...

        this.enter(target, 'Buying this one because...');
    },

    // called when it has an open position
    onManage: function(target, position, data){

        // your code to check if it should exit the position...

        this.exit(position, 'Closing this one because...');
    }
});

What is a Parameter?

When you create a Strategy, you are defining a model of the rules, processes and/or data for a specific trading strategy. That model and its rules will have predefined variables that a user can provide custom values for each time they use that Strategy. In Alta5, those variables are defined using Parameters. Parameters are defined in the params array of the strategy definition.

Example rule in plain english:

if the current RSI value is less than signal then buy.

if the risk/reward ratio value is greater than ratio then sell.

In the rules above, signal and ratio would be the variables for which we would define Parameters.

What is a Target?

In Alta5, Traders using a strategy seek and manage positions in 1 underlying security. That security is the Target Security for that Trader. A Strategy can have an unlimited number of Traders, each with a different target and settings.

The type property controls how the target security is chosen by a user when creating a Trader using the strategy, using a security field (Targeted) or by choosing a cover position (Covered). The default is Targeted. To restrict the strategy to being used with only 1 hardcoded target security, set the target property directly. A default target symbol can be provided using targetDefault. The "type" of security the strategy is intended to target can be set using targetType. The default is Security.ANY.

Strategy Setup

Config Options

All strategy definitions are required to have properties that define the name, description, positionType and params for the strategy. Properties are configured using standard JavaScript object property name:value pairs.

The following properties are available to configure a strategy:

closeTime

Number

A number representing a time (in 24 hour format) for traders using this strategy to close, even if the market is still open.

If a negative number is used, it will be subtracted from today's Market close time to produce the trader close time. The negative value must be in the same 24 hour format.


closeTime: 1315,   // close at 13:15 (1:15pm)

closeTime: -30,   // close 30 minutes before the market closes

closeTime: -200,   // close 2:00 hours before the market closes

description

String
A short description for the strategy.

enterAction

String
The action for an enter trade made by this strategy. Not valid for strategies that trade spreads. For equity positions: Trade.BUY (default) Trade.SELL_SHORT For option positions: Trade.BUY_TO_OPEN (default) Trade.SELL_TO_OPEN

exitAction

String
The action for an exit trade made by this strategy. Not valid for strategies that trade spreads. For equity positions: Trade.SELL (default) Trade.BUY_TO_COVER For option positions: Trade.SELL_TO_CLOSE (default) Trade.BUY_TO_CLOSE

forceDayTrade

Boolean
True to override the default day trading settings to allow day trading by this strategy. false

itmMinutes

Number
The number of minutes before expiration to exit any option position or spread that is in the money. Only valid for strategies that are trading options. 5

itmMinutesMemo

String
The memo for the exit trade. 'Automatic exit of ITM position before expiration.'

name

String
The display name for the strategy.

openTime

Number

A number representing a time (in 24 hour format) for traders using this strategy to open, even if the market is open earlier.


openTime: 1000,   // open at 10:00 (10am)

openTime: 1330,   // open at 13:30 (1:30pm)

params

Array
An array of objects with parameter configurations for this strategy.

See the Parameters guide for more information.

positionType

String
The type of position this strategy will be seeking and managing. Position.EQUITY - Equity Position.OPTION - Option Position.SPREAD_CREDIT - Credit Spread Position.SPREAD_BULLPUT - Bull Put Spread Position.SPREAD_BEARCALL - Bear Call Spread

pricer

Object
Override the system Smart Pricing settings. Smart Pricing attempts to fill a trade with multiple limit price stops between the bid/ask spread. stepsNumber The number of price stops to use when smart pricing. 5 intervalNumber The number of milliseconds to wait for each price stop to fill. 5000

// 3 price stops for 10 seconds each
pricer: {
    steps: 3,
    interval: 10000
}

target

String
A fixed symbol to use as the target for all traders using this strategy. Users of the strategy will not be able to select a target.

This property is not used by Covered strategies.

targetDefault

String
A symbol to use as the default target for new traders. The value will automatically be filled into the target field in the Alta5 application but users will be able to change it. To set a fixed target that can't be changed, use the target property above.

This property is not used by Covered strategies.

targetType

String
Sets the "type" of target this strategy was designed to trade. The target input field in the Alta5 application will give feedback to users of the strategy based on this setting.

This property is not used by Covered strategies.
Security.ANY - Any target Security.ACTIVES - Targets with actively traded options Security.WEEKLIES - Targets with weekly options Security.ANY

tradeTimeout

Number
The default timeout value for trades made by the strategy (in seconds). 60

type

String
Defines the type of strategy. Targeted - A strategy that seeks funded positions in a target security. The target security for a Targeted strategy trader is set using a special symbol field. Covered - A strategy that uses a cover position to secure positions. The target security for a Covered strategy trader is automatically set to the security of the selected cover position. Targeted

waitTime

Mixed
The amount of time to wait to start seeking a new position after closing a position. A String duration to wait, i.e. '15m' or '1h' or '2d' 'tomorrow' - next market open. 'nextweek' - first market open next week, generally monday. A Date object in the future

workers

Array
An array of objects with worker configurations for this strategy.

See Workers below for more information.

Example

This example changes the default strategy enterAction/exitAction to sell the target stock short.


Strategy.define({
    name: 'My Strategy',
    description: 'This is a test strategy.',
    positionType: Position.EQUITY,
    enterAction: Trade.SELL_SHORT,
    exitAction: Trade.BUY_TO_COVER,

    params: [{
        id: 'overboughtSignal',
        group: 'Signals',
        type: 'number',
        label: 'Overbought',
        min: 1,
        max: 100,
        defaultValue: 70
    }]
    ...
});

Parameters

Parameters are used to provide customizable values to a Trader using the strategy. Parameters accept many configuration options and validation rules. Those options and rules are documented in the Parameters guide.

Configuration

Parameters are defined in the params array in the strategy definition and are configured when defined using standard JavaScript object property name:value pairs.


params: [{
    id: 'indexSecurity',
    type: 'security',
    description: 'Choose an index to monitor.'
},{
    id: 'maxValue',
    type: 'number',
    label: 'Max Value',
    min: 1,
    max: 100
}]

Accessing Values

Parameter values can be accessed in a strategy method using the parameter id as a property of the Trader's data object or by calling the get method of the Trader.

Using data:


params: [{
    id: 'maxValue',             // id = 'maxValue'
    type: 'number',
    label: 'Max Value',
    min: 1,
    max: 100
}],

onSeek: function(target, data){
    // get from data
    var max = data.maxValue;    // so the value is available as 'maxValue'

    // ...
}

Using get:


params: [{
    id: 'maxValue',
    type: 'number',
    label: 'Max Value',
    min: 1,
    max: 100
}],

onSeek: function(target, data){
    // Using get() with optional default value (50)
    var max = this.get('maxValue', 50);

    // ...
}

Guide

See the Parameters guide for more information about parameters.

Workers

Workers are responsible for all asynchronous "work" a strategy needs to analyze or load data. A strategy will not run unless all of its workers are ready, signaling that their work has been performed successfully and any data they are responsible for loading is available.

Methods implemented in a strategy, i.e. onSeek or onManage, should not contain asynchronous code. All asynchronous code belongs in a Worker.

Configuration

Workers are configured when defined using standard JavaScript object property name:value pairs. To reference a Trader property or parameter value to configure a worker property, use $ with the name of the property or parameter: security:'$target'.

Example:


workers: [{
    id: 'chain',
    type: 'optionchain',
    security: '$target',            // reference the target symbol
    maxSeries: 2,
    optionType: OptionChain.CALLS,  // out of the money calls
    range: OptionChain.OTM
}]

Accessing Worker Data

When a worker is ready, it's data (i.e. a chart, an option chain, a security) is available to the Trader with it's id as the property name in the Trader's data object or by calling the get method of the Trader.

Using data:


workers: [{
    id: 'chain',                // id = 'chain'
    type: 'optionchain',
    security: '$target',
    optionType: OptionChain.CALLS,
    range: OptionChain.OTM
}],

onSeek: function(target, data){
    // get from data
    var chain = data.chain;     // so the option chain is available as 'chain'

    // ...
}

Using get:


workers: [{
    id: 'chain',
    type: 'optionchain',
    security: '$target',
    optionType: OptionChain.CALLS,
    range: OptionChain.OTM
}],

onSeek: function(target, data){
    var chain = this.get('chain');

    // ...
}

Worker Types

The following workers are bundled with Alta5:

Security

security

Loads and initializes a Security object for a symbol. The symbol can be a fixed value (e.g. 'AAPL') or bound to a parameter.

Usage:


workers: [{
    id: 'vix',            // available as data.vix
    type: 'security',
    symbol: 'VIX'
}]

See the Securities guide for detailed information about using Security workers.

Option Chain

optionchain

Loads and initializes an option chain for a Security and optionally creates spreads.

Usage:


workers: [{
    id: 'chain',
    type: 'optionchain',
    security: '$target',            // use the target symbol

    optionType: OptionChain.CALLS,  // only calls
    range: OptionChain.OTM          // out of the money
}]

See the Option Chains guide for detailed information about using Option Chain workers.

Chart

chart

A virtual chart with bar data and indicators for technical analysis.

Usage:


workers: [{
    id: 'chart',
    type: 'chart',
    security: '$target',              // use the target symbol

    interval: Chart.Interval.DAILY,   // daily bars
    periodType: Chart.Period.DAY,     // for 30 days
    periodCount: 30,

    indicators: [{
        type: 'rsi',                  // RSI indicator
        timePeriod: 14
    }]
}]

See the Charts and Indicators guide for detailed information about using Chart workers.

Intraday Chart

ichart

A live streaming intraday chart for today with bar data and indicators for technical analysis.

Usage:


workers: [{
    id: 'ichart',                     // available as data.chart
    type: 'ichart',
    security: '$target',              // use the target symbol
    interval: Chart.Interval.MINUTE,  // minute bars
    minBars: 26,                      // for macd, wait for 26 bars before being "ready"

    indicators: [{
        type: 'macd',                 // MACD indicator
        fastPeriod: 12,
        slowPeriod: 26,
        signalPeriod: 9
    },{
        type: 'mom',                  // Momentum indicator
        timePeriod: 12
    },{
        type: 'rsi',                  // RSI indicator
        timePeriod: 14
    }]
}]

See the Charts and Indicators guide for detailed information about using Intraday Chart workers.

Custom Workers

See the Custom Workers guide.

Trader Properties

Traders expose properties at run-time that can be accessed by Strategy methods and workers using this.propertyName.

Reference

ordering

Boolean
True if this Trader has an active order in progress.

paused

Boolean
True if this Trader is paused.

position

Position
The active position for this Trader.

ready

Boolean
True if this Trader is initialized, funded and all of its workers are ready.

simulating

Boolean
True if this Trader is paper trading. true

target

Security
The target security for this Trader. Can be used as $target to configure a worker's security.

Methods

Strategies are implemented using predefined template methods that are error safe and automatically subscribed to any necessary events. Methods implemented in a strategy should not contain asynchronous code. All asynchronous code belongs in a Worker.

Required Methods

Every strategy must implement the methods onSeek and onManage to seek new positions and manage open positions. onSeek is called when a Trader using the strategy is scanning for a position and onManage is called when the Trader has an active position.

onSeek

Security target, Object data
Called every Market tick when the Trader is ready and seeking a new position. Generally scans available market data for specific entry conditions. targetSecurity The target security for this Trader (this.target). dataObject An object containing properties with parameter values and any data loaded by workers. The property name for values is the id of the parameter or worker.

onSeek: function(target, data){
    // get the chart
    var chart = data.todayChart;

    // get the last bar in the chart
    var bar = chart.lastBar;

    // get the RSI value of the last bar
    var rsi = bar.indicator('rsi');

    // trace the RSI value in Strategy Studio for debugging
    data.rsi = rsi;

    // get the Bollinger Bands values
    var upper = bar.indicator('bbands', 'upperBand'),
        mid = bar.indicator('bbands', 'middleBand'),
        lower = bar.indicator('bbands', 'lowerBand');

    // ... do something useful with the values
}

onManage

Security target, Position position, Object data
Called every Market tick when the Trader is ready and has an active position. Generally scans available market data for specific exit conditions. targetSecurity The target security for this Trader (this.target). positionPosition The active position for this Trader. dataObject An object containing properties with parameter values and any data loaded by workers. The property name for values is the id of the parameter or worker.

onManage: function(target, position, data){
    var bar = data.chart.lastBar,
        macd = bar.indicator('macd'),
        signal = bar.indicator('macd', 'signal'),
        rsi = bar.indicator('rsi');

    // values added to 'data' are visible in Strategy Studio debugging
    data.macd = macd;
    data.signal = signal;
    data.rsi = rsi;

    // macd cross under
    if(macd < signal){
        return this.exit(position, 'MACD cross under');
    }

    // rsi overbought
    if(rsi >= this.get('overboughtSignal')){
        return this.exit(position, 'RSI overbought');
    }
}

Enter a Position

When the onSeek method of a strategy finds a position it wants to open, it initiates the entry of a new position by calling the Trader's enter method.

enter

Mixed security, String memo, Number quantity
Initiates a trade to enter a new position. By default, enter will create a trade for the maximum quantity of the passed Security or Spread this Trader has funds to enter. You can override that behavior by passing a custom quantity. securityMixed Any Equity, Index, Option or Spread. memoString A memo to include on the created trade and position. quantityNumber A custom quantity for the trade. Using a custom quantity overrides Alta5's built-in risk controls.

Example


onSeek: function(target, data){
    var bar = data.chart.lastBar,
        rsi = bar.indicator('rsi');

    if(rsi <= data.overboughtSignal){
        var option = data.chain.firstSeries.getCallAbove(target.last);
        this.enter(option, 'RSI Overbought: {0}'.format(rsi));
    }
}

Exit a Position

When the onManage method of a strategy determines it wants to close a position, it initiates the exit of the position by calling the Trader's exit method.

exit

Position position, String memo, mixed waitTime
Initiates a trade to exit a position. By default, exit will create the appropriate type of trade to exit the type of Position passed as the first argument. positionPosition Any type of Position. memoString A memo to include on the created trade and position. waitTimeMixed Override the default Trader waitTime setting. Controls how long to wait before seeking a new position. A String duration to wait, i.e. '15m' or '1h' or '2d' 'tomorrow' - next market open. 'nextweek' - first market open next week, generally monday. A Date object in the future

Example


onManage: function(target, position, data){
    var bar = data.chart.lastBar,
        rsi = bar.indicator('rsi');

    // rsi overbought
    if(rsi >= data.overboughtSignal){
        return this.exit(position, 'RSI overbought: {0}'.format(rsi));
    }
}