Trade Smarter with Automation

Intro to Alta5

Learn the basics of bot trading with Alta5.

Bear Bounce

  • - Watchlist
  • - Inputs
  • - Controls
  • - Routines

1 Create a bot prototype. Learn how in this guide.

  Start Bot
Start Bot

2 Click "Start bot". Set variables & risk controls for the new bot.

Bear BounceAAPL
Bear BounceLVS

Bear BounceMSFT
Bear BounceMON

3 Start multiple bots from your prototype, each with custom settings. (optional)

What is a bot prototype?

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 routines to research additional data, look for opportunities (scan) or checking on existing ones (monitor).

In Alta5, a prototype is a blueprint that defines the variables, controls and routines for a bot to repeat your trading plan. When buttons are pressed or events are triggered, bots execute instructions you provide in JavaScript.

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


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 prototype 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:


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 bot's watchlist is defined a variable, e.g. $gold to represent GLD. That variable has properties (e.g. $ 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 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 prototype and a form field will to displayed to provide a value when starting a bot:


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')
        $vix = snap; //  <-- $vix is defined until restart


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){

Stored data
Since state variables, and other types of stored data are persisted in a database, there are some logical restrictions. Stored data must only contain:

• Primitive values (number, string, boolean)
• Date objects
• Arrays & objects containing only primitive values and Date objects

All other values are ignored and will not be stored. Stored data cannot contain any references to run-time objects returned by the $data API.


Bots have hooks that are triggered daily and other hooks that are triggered by activity. When you build your bot, you add routines (scripts) that are executed when a bot hook is triggered. Below is a list of the available hooks for your routines and when they are triggered:

Hook When... Notes
 setup the bot starts (daily) Used to setup buttons and other controls.
 wake the market opens (weekdays) Generally used to load data and/or calculate signals.
 tick,  scan and/or  monitor are triggered once per second the market is open, the wake event is done and all requested data is loaded tick is triggered right before scan or monitor.

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.
Triggered by activity
 open the bot opens a new opportunity Can be used to leg into opportunities, reload data, etc.
 close the bot closes an opportunity "
 cancel the bot cancels an opportunity Can be used to retry and/or adjust prices when an opportunity times out.
 load $bot.reload() is called Used to reload data and/or recalculate signals.
 error the bot has an error $bot.message has the error message.
 pause the bot is paused $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 bot, you will generally load any data needed using a wake routine. $data is also available in other async bot hooks 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:

    // 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'
    // 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:

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


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 the prototype settings. The default limit is 1 open opportunity at a time.

Example scan routine:

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

Opening a new opportunity

Opportunities are opened by calling $ 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:

    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.

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.

    type: 'call',
    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.

    type: 'call',
    symbol: 'JPM',
    expiration: 'next friday',
    strike: 55,
    price: {
        min: 1.3,
        max: 1.45

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.

    type: 'call',
    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

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

Manual Prices

You can also specify prices manually:

    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. The default timeout is 5 minutes.

    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 the day.
  • '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.

    type: 'equity',
    symbol: 'JPM',
    price: 55.23,
    quantity: 100

Monitoring opportunities

When the market opens each weekday, after the wake event is done, a bot starts triggering the monitor event multiple times per second if it has any open opportunities. Your monitor script can check for profit taking, stop loss or any other condition that should trigger the bot to close an opportunity.

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];


var opp = $bot.opp;


Below is the monitor routine from the HighRise sample bot. 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.

    $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 prototype, your can start a bot 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.
  • Risk - Trading account and 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. For more info see the Capital & risk controls guide. 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 building a prototype, the "Bots" list in the prototype builder provides an easy to use interface to manage bots using it:

  • Upgrade - Upgrade bot to the latest prototype.
  • 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.


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