Automated Trading Examples

Common Examples

Note that in these examples we use a set of API keys called Keys and a generic symbol/market ticker of symbol. You would need to replace these with the name you gave your API keys, and the symbol you want to trade, such as XBTUSD.

We also assume the units to buy and sell are measured in contracts, like on BitMEX, but this varies by exchange and market. (eg, on BitMEX, a trade of size 100 is about $100, while on FTX BTC-PERP it would be 100 BTC!)

Simplest trade possible

In this example we'll just execute a basic market order. Market orders will just attempt to buy or sell an amount, regardless of your current position or balance, so the order can fail if you have insufficent funds.

Keys(symbol) {
    # Buy 100 contracts NOW
    market(side=buy, amount=100);
}

How about if we want to spend a percentage of our balance, instead of a fixed 100 contracts. We can do the following (notice the amount).

myApiKeys(XBTUSD) {
    # Buy NOW, using 10% of my balance
    market(side=buy, amount=10%);
}

Learn more about the commands used here...


Flip from Long to Short, or Short to Long

This would need two alerts. One that is triggered when you get a LONG signal, and one when you get a SHORT signal.

First some examples of going long. These will all work regardless of your current position size (regardless if you are long or short)

Using market orders

# Long Signal
Keys(symbol) {
    # Close any existing position (eg a short)
    market(position=0);

    # Go long
    market(side=buy, amount=90%)
}

Using market order with position

# Long Signal
Keys(symbol) {
    # Calculate the size of the trade so that our 
    # final position size is 90% of our current balance
    # If we were short, this would be big enough to close the short
    # and open a long at the same time.
    market(position=90%);
}

Using limit order with position

# Long Signal
Keys(symbol) {
    # Cancel any outstanding orders
    cancel(which=all);

    # calculate the trade size so that we end up long 90% of our balance
    aggressive(position=90%);
}

and now a few variations on this to handle the short signal...

Using market orders

# Short Signal
Keys(symbol) {
    # Close any existing position (eg a short)
    market(position=0);

    # Go long
    market(side=sell, amount=90%)
}

Using market order with position

# Short Signal
Keys(symbol) {
    # Trade the amount need to end up short position 
    # that is 90% of our current balance
    market(position=-90%);
}

Using limit order with position

# Short Signal
Keys(symbol) {
    # Cancel any outstanding orders
    cancel(which=all);

    # Ends up short 90%, from any starting 
    # position size (none, long, already short, does not matter)
    aggressive(position=-90%);
}

Place a Stop Loss at Breakeven when first Take Profit is hit

In this example, we will open a position and then set 2 take profits (at 1% and 2% in profit). When the first take profit is it (at 1%) we will also place a stop loss order at breakeven.

myApiKeys(XBTUSD) {
    # Open the initial long position
    market(position=100%);

    # Place 2 take profit orders at 1% and 2% up from entry
    # Each one will close 50% of the open position
    limit(side=sell, amount=50%p, offset=e1%);
    limit(side=sell, amount=50%p, offset=e2%);

    # Finally, place a trailing take profit order that we will actually
    # use to place a fixed stop loss at breakeven when the first TP is reached.
    trailingTakeProfit(side=sell, amount=100%p, 
        triggerOffset=e1%, offset=1%, 
        trailingMethod=none,
        trigger=last, reduceOnly=true);
}

The way the Stop Loss at breakeven works is quite interesting. The way trailingTakeProfit works is to first wait for the price to reach some target (triggerOffset in the example above). When it gets to that trigger point it then places a trailingStopLoss. In the example, this uses the same offset again, so the order was triggered 1% above average entry, and when it's triggered it places a trailing stop loss order 1% below the price (ie, at break even). It then sets the trailingMethod to none, so despite the command name it does not actually trail. Instead, the stop loss order just appears at break even, and stays there. Awesome!


Only trade if a certain condition is met

There are 2 commands to help with this. continue() will only continue to the commands after it, if it's condition is met. stop() will stop execution (and not execute the commands after it), if it's condition is met.

So if we only want to trade if we have an open long position, we can do this...

Keys(symbol) {
    # Here we test a condition (the If...)
    continue(if=positionLong);

    # We are long, do things we want to do when long
}

Only trade if a certain condition is NOT met

To say we'd like to continue if a condition is met, is the same as saying we'd like to stop if the condition is not met.

If we only want to trade if a condition is NOT met (for example, trade if we are NOT long - flat or short), then we can use stop() to stop us if we are long. If we are not long, then we'll continue to the commands below...

Keys(symbol) {
    # Make sure we are NOT long (ie we are short OR flat)
    stop(if=positionLong);

    # We are not long, do things we want to do when we are flat or short
}

Only trade if condition A is met AND condition B is met

If we want to be sure two conditions are met before we will trade, then we can use more than one continue() or stop() command...

Keys(symbol) {
    # Make sure we are long
    continue(if=positionLong);

    # AND make sure our position is less than 5000 contract
    continue(if=positionSizeLessThan, value=5000);

    # We are long and have a position less than 5000
    # do things we want to do here
}

If Then Else

If you want to do one of two things and you can test it with one of the conditions availabel in continue() or stop(), then you can create if then else style setups. Here is an example...

Keys(symbol) {
    # Here we test a condition (the If...)
    continue(if=positionLong);
    wait(3s);

    # We are long, do things we want to do when long
}

Keys(symbol) {
    # this is the opposite of the first condition (the Else...)
    stop(if=positionLong);
    wait(3s);

    # We are NOT long (could be flat, could be short)
    # Do things we want to do when we are not long
}

It works by having 2 blocks in the alert message. One block handles the case of your condition being true, and the other block handles the case of the condition being false.

You might be wondering why there is a wait() command in there too. The reason for this is to ensure both blocks get a chance to test their conditions with the exchange in the same state. While both sets of commands are run at the same time, the bot makes no guarantee about the exact order things will play out. Without the wait, one of the 2 blocks might execute, place some orders and generally change the state on the exchange in a way that means the other slightly delayed block also passes it's conditions.

To be sure you always get one OR the other, add the wait().


Trade on two exchanges / accounts at the same time

If you need to trade on two exchanges, or multiple accounts on the same exchange, then you can do that as follows...

Add all the API keys to Alertatron, then duplicate the scripts in your alert message, once for each API key you want to use.

FirstAccount(symbol) {
    # The trades to execute on this account
    market(side=buy, amount=100);
}

SecondAccount(symbol) {
    # The trades to execute on this account
    market(side=buy, amount=100);
}

The trades for each account will be executed at the same time, though there will be a slight delay between each account starting to avoid various timing and connection related issues.

If you have a lot of accounts, you may find our support for Trading Groups is a better solution.

Some images from Unsplash

About Alertatron.com

Your TradingView alerts, with charts, PM'd to you.

Get all your alerts from TradingView, sent to Telegram, Discord, Slack, Email or webhooks, with a chart snapshot attached.

Capture Charts

See a high quality chart with every alert, captured at the moment the alert was triggered. See exactly what the market was doing and make informed decisions.

Automate Trading

Trigger orders on popular cryptocurrency exchanges and trade 24/7. Access powerful algorithmic orders to maximise your profits.

Integrations

Connect your alerts to Telegram (channels, groups and private chats), Discord, Slack, email or send push notifications to other services with webhooks.

Easy To Setup

Nothing to install and no browser extensions. Captures alerts 24/7, even with your computer switched off. Be up and running in seconds.