Trade Smarter with Automation

Intro to Alta5

Automate your financial future.

Bear Bounce

  • - Watchlist
  • - Inputs
  • - Events

1 Create your strategy. Learn how in this guide.

  Start Bot
Variables
AAPL
30
2
Start Bot

2 Set variables and capital options to start a bot.

Bear BounceAAPL
Bear BounceLVS

Bear BounceMSFT
Bear BounceMON

3 Start an army of bots trading your strategy.

What is a strategy?

As a young investor, I frequently made trades based on a hunch or my "gut". I rarely hedged properly and often made irrational trading decisions based on the state of my emotions in the moment.

Eventually, I learned that I need to have a strategic plan when investing. That plan should clearly define when to get in, when to get out and how to hedge downside risk. Having a plan helps me to avoid mistakes by removing emotions and "gut" from my trading decisions.

When actively trading the market, I tend to repeat a pattern that includes: watching stocks in a watchlist, calculations with a few key numbers (variables) and reacting to events by researching additional data, looking for opportunities (scan) or checking on existing ones (monitor).

In Alta5, a strategy is a blueprint that defines the data, variables and events for a bot to repeat your trading plan. When the specified events are triggered, bots execute instructions you provide in JavaScript.

There are several sample strategies available under build in the application that you can install and edit to practice building your own strategy.

Variables

Google defines a variable as:

In Alta5, your bot is the program and variables are used to represent stocks, numerical values, charts or any other value that you want your bot to be able to analyze. Every strategy defines the set of variables for its bots. Variables are available globally for each individual bot and are prefixed with a $ to make them easily distinguishable in code (e.g. $stock).

Variables can be defined in the following ways:

Watchlist

A bot's watchlist is similar to the watchlist you use in your favorite trading program. The image below is a screenshot of my watchlist in thinkorswim. Each row in the watchlist has several columns of data about a security. When actively trading, I monitor the values in those columns to help me make more informed trading decisions.

In Alta5, each item in a strategy's watchlist is defined a variable, e.g. $gold to represent GLD. That variable has properties (e.g. $gold.bid) that contain the real-time values displayed in the thinkorswim columns (and many other values) that your bots can analyze as you do. You can find out more about properties available in the Security API docs.

Inputs

Inputs are variables whose values are set when starting each bot. Each input corresponds to a number, boolean, date or text form field for you to provide the value for that bot.

For example, you watch for an opportunity to sell a put spread if the potential return is greater than 10%. If you want the number 10% to be customizable per individual bot, you can add a number input named $returnRate to your strategy and a form field will to displayed to provide a value when starting a bot:

Code

You can define a new bot variable in code by prefixing the variable name with $. Variables defined in code are reset each time the bot restarts (generally once per day). For example:

$data.snapshot('VIX', 'yesterday')
    .then(function(snap){
        $vix = snap; //  <-- $vix is defined until restart
        $done();
    });

State

Each property set on $bot.state is also defined as a variable, available indefinitely across bot restarts. For example, if you set a state property named "phase":

$bot.state.phase = 2;

Then a new variable, $phase, is available globally for that bot:

if($phase === 2){
    ...
}

Since state variables are saved in the database, they can only contain primitive values (number, string, boolean or Date) or an array/object containing only primitive values.

Scripts

Scripts contain instructions, in JavaScript, executed when a specified event is triggered for a bot. Every strategy will generally have scripts for wake, scan and monitor events. Scripts can reference any bot variable, load data, monitor opportunities, etc and are used to define the logic for your strategy.

When... Event(s) Notes
the market opens daily wake Generally used to load data and/or calculate signals.
the market is open, the wake event is done and all requested data has loaded scan and/or monitor are triggered repeatedly scan is triggered if the number of open opportunities is less than the strategy's opportunity limit.

monitor is triggered if the bot has an open opportunity.
$bot.reload() is called load Used to reload data and/or recalculate signals.
the bot opens a new opportunity open Can be used to leg into opportunities, reload data, etc.
the bot closes an opportunity close "
the bot has an error error $bot.message has the error message.
the bot is paused pause $bot.message has the pause message.

Loading data

The $data API provides access to stock quotes, charts, option chains, spreads and other data useful for trading. When creating a strategy, you will generally load any data needed using the wake event. $data is also available in other async bot events and the Alta5 console.

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 generally 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
});

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
    });

Opportunities

Alta5 adds a layer of automation for working with equity, option and complex positions. Positions are opened and closed by opening and monitoring opportunities. Automation handles price, quantity and capital draw or they can specified manually for each opportunity.

Scanning for opportunities

When the market is open, after the wake event is triggered, a bot starts triggering the scan event multiple times per second to search for new opportunities. Any data required for scanning should be loaded by the wake event.

A bot will continue to fire the scan event as long as the total number of open opportunities is less than the limit set in its strategy's settings. The default limit is 1 open opportunity at a time.

Example scan event:

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

Opening a new opportunity

Opportunities are opened by calling $bot.open passing an object with option:value pairs. The type option specifies the type of opportunity you want to open. For example, to open a long equity opportunity:

$bot.open({
    type: 'equity',
    symbol: 'JPM'
});

See Opportunity API for more examples and a list of the opportunities Alta5 supports.

Smart Pricing

In the example above, you may have noticed no price was specified. Alta5's Smart Pricing feature automatically calculates the optimal price(s) when opening opportunities. This is particularly useful when opening an option or spread opportunity as Smart Pricing will automatically attempt to fill at prices between the bid/ask spread.

For example, suppose you wanted to open a call option opportunity and the bid price is $1.20 and the ask price is $1.45. Smart pricing will automatically try multiple timed limit orders between the bid/ask prices (e.g. $1.25, $1.30, $1.35, etc) until the order fills.

$bot.open({
    type: 'option',
    symbol: 'JPM',
    expiration: 'next friday',
    strike: 55
});

The number of prices and the interval for changing order prices is highly customizable:

Specific Prices

Alta5 will try to fill the order with timed limit orders at the specified prices.

$bot.open({
    type: 'option',
    symbol: 'JPM',
    expiration: 'next friday',
    strike: 55,
    price: [1.30, 1.35, 1.4, 1.45]
});
Price Range

Alta5 will calculate the prices between the min/max resulting in the same prices as the example above.

$bot.open({
    type: 'option',
    symbol: 'JPM',
    expiration: 'next friday',
    strike: 55,
    price: {
        min: 1.3,
        max: 1.45
    }
});
Custom

Price options can be combined to create completely custom order pricing. The example below would try prices $1.30, $1.35, $1.40 for 10 seconds each.

$bot.open({
    type: 'option',
    symbol: 'JPM',
    expiration: 'next friday',
    strike: 55,
    price: {
        stops: 3,     // try 3 prices
        max: 1.40,    // up to $1.40
        interval: 10  // 10 seconds each price
    }
});
Settings

Smart Pricing can also be customized globally in "Advanced Settings" in the Alta5 app:

Manual Prices

You can also specify prices manually:

$bot.open({
    type: 'equity',
    symbol: 'JPM',
    price: 55.23
});

When using a hardcoded price, you may want to use a timeout so the order doesn't sit unfilled.

$bot.open({
    type: 'equity',
    symbol: 'JPM',
    price: 55.23,
    timeout: 60   // <-- order is good for 60 seconds
});
Valid timeout values:
  • seconds: Integer specifying the number of seconds the order is valid.
  • 'day': The order is valid for the remainder of today.
  • 'gtc': The order is valid forever.

Capital, draw and quantity

Alta5 automatically calculates the quantity for orders based on capital draw settings for the bot opening the opportunity. As a simplified example, if a bot has a draw limit of $5,000 per opportunity and an opportunity draws $50 per share, the hypothetical quantity would be 100 shares. The actual calculation is much more complex as it factors in commissions, maintenance and other ways a specific type of opportunity can use capital.

Enforcing Limits

To ensure capital draw limits are enforced, the maximum potential loss is always used when calculating the quantity for an opportunity. For example, because short selling and writing uncovered (naked) puts represents a greater risk of loss of capital, the calculated quantity for any unsecured short position is calculated on a cash basis. However, the return % for an opportunity is calculated using the actual capital/margin draw according to TD Ameritrade's margin formulas.

For more info on the formulas used to calculate draw for opportunities, see TD Ameritrade's Margin Handbook.

Manual quantity

You can also specify the quantity manually. This is particularly useful for bots that open multiple opportunities at once. As a safety feature, a bot will be stopped with an error if you specify a quantity that requires capital exceeding the capital draw settings for the bot.

$bot.open({
    type: 'equity',
    symbol: 'JPM',
    price: 55.23,
    quantity: 100
});

Monitoring opportunities

When the market is open, after the wake event is triggered, a bot starts triggering the monitor event multiple times per second if it has any open opportunities. Use the monitor event to check if any open opportunities should be closed.

All open opportunities for your bot are in the $bot.opps collection. For convenience, the first open opportunity is available via the $bot.opp property.

var opp = $bot.opps[0];

or

var opp = $bot.opp;

Example

Below is the monitor event from the HighRise sample strategy. It closes the opportunity if 1 of these 3 conditions occur:

  1. The market is closing in the next 5 minutes.
  2. The opportunity has lost $stopLoss %.
  3. The opportunity has profited $targetGain %.

$stopLoss and $targetGain are number inputs.

if($a5.isClosing(5)){
    $bot.opp.close('Market closing');
}else if($bot.opp.gain <= -$stopLoss){
    $bot.opp.close('Stop loss hit.');
}else if($bot.opp.gain >= $targetGain){
    $bot.opp.close('Target gain hit.');
}

Starting a bot

Once you've created your strategy, your can start a bot that use it by clicking the Start Bot button. Starting a bot has the following steps:

  • Settings - Set standard options shared by all bots. (e.g. name, descripton, tags)
  • Variables - Set values for any watchlist or input variables defined in your strategy.
  • Capital - Set capital draw limits for the bot. (see below)
  • Review - Review settings and start your bot.

Capital draw

Capital "draw" is the amount of cash or margin a bot uses to secure its opportunities. Alta5 factors in commissions, maintenance and other ways a bot can use capital to enforce draw limits. You have 2 options to set those limits:

You can also use custom calculations in your code to manually set quantities and prices for opportunities as long as they are within the draw limits set for the bot.

Managing bots

When developing a strategy, the "Bots" list on your strategy's page provides an easy to use interface to manage bots using it:

  • Upgrade - Upgrade bot to the latest version of the strategy.
  • Debug- Debug the bot in the Console.
  • More options:
  • Restart - Restart the bot. Reloads all variables and data.
  • Reset - Give the bot a fresh start. Wipes out all stats and history for the bot.
  • Delete - Delete the bot.


What's next?

Now that you know the basics, I recommend reading one of these step-by-step tutorials:

Tasty Condor

Build a bot that collects monthly premium trading Iron Condor spreads on SPY.


Stronghold

Build a bot that buys a stock and automatically sells/rolls monthly covered calls to reduce cost basis.