How to make a cryptocurrency trading bot — Part 4

Strategst
Coinmonks
8 min readAug 1, 2020

--

Hey, hey, hey! We almost did it! The last thing is to write Alertatron messages and finish TradingView alerts.

Quick caveats:

  • Not trading advice.
  • Some others know bot-building/Pine/etc. better than I.
  • I personally have no affiliation with TradingView, Alertatron, exchanges, or any mentioned services.
  • Most products I’m showing here I use for several years already.
  • You can help this project by registering with the referral links in the post.

Ask everything about bots in My Own Crypto Bot discussions

What we are doing here:

Part zero, why I am doing this

Part One, how to generate signals with open source strategy on TradingView.

Part Two, risk management and leverage settings on BitMex.

Part Three, Alertatron setup, and BitMex API integration.

For our newest tutorials and articles subscribe to My Own Crypto Bots channel!

Let’s start with Alertatron. Don’t be scary if you have no programming experience, this service has a very simple programming language. Alertatron’s language is like normal English but written in a logical way. If you can write well-organized lists or ordered paragraphs in ordinary life, you will handle Alertatron easily.

Anyway, let me guide you word by word this time.

So, we have script added, and alerts connected to this strategy. How will it work:

When your TradingView script wants to take a trade, TradingView sends an alert to buy or sell with the Alertatron-specific code in it. Alertatron reads the code and talk to the Exchange in exchange-specific API language to execute your orders, set stops, and take profits. When executed, the Exchange tells Alertatron that is all done, and Alertatron sends your Exchange balance status in Telegram (also it has Slack and Discord integration). All this is done in seconds.

So, the last thing is to help our script to send Alertatron-specific message.

To do this, let’s look at our risk-management system in Part Two. Here we defined:

1. The initial capital of $14552.5, equals 1 BTC in dollars

2. Risking 3% of capital in every trade

3. Same Position Size of 1 BTC in every trade

4. Standard Stop loss of 3%.

and

5. In the next chapter, we will set BitMex leverage to x10 to keep liquidation price low and will trade our strategy at x33 real leverage using our own calculations.

Let’s code it!

First, we need to know that Alertatron executes our command step by step, and doesn’t go to the next line if it didn’t execute the previous line. So we have to arrange commands in order of execution.

Ok, first we need to let him know what keys it has to use for trading and what pair we want to trade.

The name of our keys on Alertatron was MyBot. We also want to trade Bitcoin/Dollar on Bitmex. The name of this instrument is XBTUSD.

Frame

In Alertatron language we can say it in one line:

MyBot is our account name, XBTUSD is our pair and inside curly brackets {} we will tell him what to do next.

Cleaning

We want to start every trade clean and cancel all orders we have pending. Also, we want to clean up leftovers like stops and TP’s from some previous orders. We are saying it like “Cancel all these things, please”, or in bots language:

Now we have:

Leverage

Next in our logic is to change the exchange setting to the exchange official leverage, it has to be less than real leverage. Let it be x10. So:

exchangeSettings is the command for changing exchange settings, and leverage = 10 means that we want our official leverage to be x10. Don’t forget semicolon ; as it tells that we are finished with the command.

How our command looks now?

With this command alone, we can change our BitMex leverage without logging on BitMex through Saved & Manual Alerts on Alertatron! But, let’s move on.

Buying

Now, let’s do “ long” command. We have three ways to buy something: by market order, which is to buy on the current offer price, by the limit order, to buy on the price you want to offer, e.g. $10 lower than the current price, or aggressive order. From Alertaron docs:

Aggressive entry order tries to enter or exit a position with a limit order that is constantly adjusted to be at the front of the order book.

So, aggressive long order will be filled right at the moment when somebody sells you her position by a market order.

Since good ol’ limit orders mechanics is more or less clear, let’s discuss the market and aggressive positives and downsides.

For the profitability and maybe more important, backtest accuracy, two things are crucial: exchange fees and slippage.

The distinct advantage of market buy is instant position switching. But there are two downsides. When we’ll try to buy in with greater than average position, like more than $100 000 in XBTUSD and much less in altcoins, there will be considerable slippage. It can hugely affect our results and make painful a difference with backtests. Also, BitMex will charge us the maker commission, so if we have $10000 position, we’ll pay 0.075 commission, which will be $15 commission for position switching (sell $10k short and go $10k long). So for 1000 trades, we will realize $15000 of fees spending, no difference are we making profits or suffering losses.

In an aggressive option, there is a chance to chase the price for a considerable time, so we can suffer same slippage, but with exchange paying us, though we can limit our slippage. Often we’ll have an opportunity to fill the order on the same price as a signal comes without chasing it and with “taker” commissions. Aggressive orders are much more profitable on liquid exchanges when we can fill the order closely to signal price. Additionally, Bitmex or Bybit pays us a negative (-0.025) commission for that type of orders. So for 1000 trades, we realize $2500 profits from the exchange for just switching our positions.

We should consider distinct types of orders for different types of strategies. In this strategy the alert comes right after the first strong move and price usually rests some time on the same level, so we’ll use aggressive order to increase profitability.

We’ve decided to use an aggressive type of order, now we have to decide our position size. Have to say that Alertatron execution is very smart, so it is enough for it to tell what target position do you want — positive (for longs) or negative (for shorts) and what exact quantity or percentage of capital do you want.

How to calculate the leveraged position in Alertatron? Multiply your allocated capital per trade (we’ve allocated 3%) and your real leverage (our is x33). The result is 99%, which is close enough to the amount we want to trade — 1 BTC. But if we want to use 5% of capital with x45 leverage for some another strategy, we will use a position of 225%.

Okay, that is all, so we write the following thing:

Here aggressive stands for an aggressive type of order, and position has a positive sign. That means we want to long. The formula for position calculation is Leverage * Allocated Capital.

“Position” function can be used in other ways, e.g. you can set fixed position, like $5000.

or if you want to have a negative position for shorts, put minus sign ahead of the number

One cool thing Alertatron can do is to calculate delta — the difference between the position you have and position you want, so when your position is 3000 and you sending new command aggressive(position = -8000); Alertatron will calculate that first, it has to sell not only 8000 to go short, but additionally 3000 to close your long, so it will sell 11000 in total. So just write the target position you want to have and enjoy!

Now our code looks like that:

Stop loss

Now about stops. We have a 3% stop loss from our risk management and want to stop by market order to exit position very quickly.

StopMarket is the command for stops and Market stands for a market order. The target position is 0, which means we need to sell everything at that moment. Offset from the entry price is 3% as we wanted. Last, the exchange will sell our position when the last XBT price hits the stop loss level. There are other triggers, as the documentation says: Index represents the underlying index price, mark is the mark price and last is the last traded price.

In other words, all other triggers will wait some time before stop you, it can be painful in the case of well-known Bitmex wicks happens, but can save your position if the price returned to the starting position very quickly.

Balance

Aaaand… Sent me a Telegram message with my wallet numbers, but first, make sure that the position is long.

Okay, that is our long alert and a draft for short alerts.

Selling

For shorts, we have to change the sign of our position to minus

and condition for balance sending

No need to change the “offset” sign in stopmarket function.

Now we have all alerts done.

Let’s add some meaningful message for Telegram.

TradingView Alerts

Go to TradingView alerts and open Buy alert.

Paste that long red “Webhook” link in the small window in “Alert Actions” and check “WebHook URL”, then paste our code for long.

Then do the same for shorts.

Congrats!

You’ve created your first bot. Now you can close all your windows and grab some coffee while waiting for next alert to come. Your own bot will start trading by itself with defined strategy. No emotions, cold-blooded, and tested!

If you have any questions about this tutorial, bot building, TradingView, Pine, or Alertatron, join us in our My Own Crypto Bot discussions!

To receive more tutorials like this, more reviews and articles about automatic trading Subscribe to My Own Crypto Bots channel!

Also, Read

--

--