Building Crypto Trading Bots with Python

Check out our new platform: https://thecapital.io/

ShrimpyApp
The Dark Side
14 min readOct 3, 2020

--

Developing trading bots doesn’t need to be complicated.

You’ve read the other tutorials. That’s probably why you’re here. You are looking for an easier way. Instead of a cryptic tutorial with thousands of lines of code just to connect to an exchange, you want a quick script and simple logic.

You’re in the right place.

This tutorial will be as complete as possible, but getting started can take under 15 minutes.

Some of the topics we will cover include:

  • Collecting asset pricing and trade data
  • Accessing snapshots of exchange order books
  • Linking an exchange account
  • Retrieving balance data from an exchange account
  • Executing a trade
  • Getting chart candlesticks

Throughout the remainder of this tutorial, we will provide precise examples and sample code for how to quickly begin performing common functions with trading bots.

Note: All code provided in this article is for example purposes only. The code should not be used in production. We won’t provide any error handling or discuss best practices for production code.

Purpose of using trading bots

Trading bots are ideal for automating trading strategies that are difficult to implement manually. These automated strategies can take advantage of rapid movements in the market, precise order execution, and specific configurations.

Trading manually is trading at a disadvantage. In the age of computers, trading bots have significant advances over trading manually. Throughout this tutorial, you will be equipped with the tools to implement your own automated trading system.

Getting Started

Before we can start trading, we will need to install the necessary libraries, obtain API keys, and configure our setup. The first time you go through the setup it may feel cumbersome, but we will quickly see that after our environment is ready, development is a breeze.

Sign up for the developer APIs

Join the Universal Crypto Exchange APIs by signing up for a new account.

Note: Executing trades through the developer APIs is possible with the $19/mo “personal” payment plan.

Creating and securely storing API keys

Inside the application interface, select the option for creating an API Master Key on the “API Keys” page.

Create an API Master Key by selecting the orange button.

A popup will request you to enter your password and 2FA code. If you haven’t enabled 2FA yet, you can do this in the “Settings” tab.

Enter the necessary information to verify your account.

The final verification step is a message that will be sent to your email. Click on the link in the email that is sent to verify the creation of the API keys.

Click on the link that is sent to your email.

Your developer API keys will become visible once the link sent to your email is clicked.

Notice: The public API key is shown by default, however, the private key is hidden. After selecting to “Show” the private key, you will never be able to see the private key again. Make sure to securely store your API keys in a safe location. If any part of your key is lost, you can always create a new key from scratch.

Select the “Show” button to view the private API key.

Do not ever show these API keys to anyone, unless you would like them to have complete control over your account.

Securely store the API public and private keys

Finally, there is only one more step for setting up our API keys. That step is to enable all of the permissions possible on the API keys. These permissions can be changed later, but for this tutorial, we will need all of the permissions enabled.

Update the API keys to have all of the permissions enabled.

Now that we have successfully set up our API keys, let’s subscribe to the $19/mo “Personal” plan. This will be required to execute the trades in this tutorial.

Select the option for the “Personal” plan and begin the subscription.

That’s it for the API keys setup!

Set up your Python environment

Now that we have our API keys, it’s time to set up our Python environment. Start by installing any version of Python 3. Once Python 3 is installed, install the Shrimpy Python Library by running the following command.

There are a few other libraries that we will need for the different tutorial scripts. In addition to the Shrimpy Python Library, install Pandas and Plotly.

Create our exchange API keys

That’s right, there are more API keys that we need before trading on an exchange. In addition to the Shrimpy API keys, we will need to create API keys on the exchange of our choice.

Don’t worry, once these keys are connected to Shrimpy, we won’t need to keep them anymore. Shrimpy will automatically manage our API keys for us, so we don’t need to implement our own API key management system.

Creating an exchange API key should be done on your exchange account. You can find tutorials on how to access API keys from each exchange here.

After getting to the step where the API key is copied out from the exchange, you can stop following the help article at that time and come back to this article. Make sure you have securely stored your exchange API keys so we can plug them into our Python scripts where necessary.

Writing Python Scripts

Our setup is complete, so it’s time to jump into writing code! This is the exciting part, so buckle up and get ready to start automating your cryptocurrency.

Comment: Your Shrimpy API keys should be securely stored where you can access them. Whenever you see the following lines in a script, that means you should replace the … with your actual Shrimpy API keys. Notice, the word “Secret” is interchangeable with “Private” when referencing API keys.

Comment: Your exchange API keys should be securely stored where you can access them. Whenever you see the following lines in a script, that means you should replace the … with your actual exchange API keys. Notice, the word “Secret” is interchangeable with “Private” when referencing API keys.

Collect pricing data from the exchange

We will start by covering the scripts you will need to get started with collecting data from the exchange.

Although trading is our ultimate goal, we require data to decide when is the appropriate time to trade. It’s also necessary to have order book data to calculate the precise order we want to place.

Getting simple price ticker data

When precision isn’t necessary, we can use the ticker price. The simple price ticker is ideal for display purposes and getting a general sense of the price of an asset.

The simple price ticker should not be used to make trading decisions.

After seeing this script, you might be asking yourself, “That’s it?”.

That sure is it!

Let’s crank up the intensity by diving right into a price ticker example using websockets.

Getting a live price ticker using websockets

The trade websockets can be used to obtain a live price feed for assets. These live updates are the exact trades that are being executed on the exchange. This live data can be used to decide when to trade.

Since the process for connecting to websockets is a little more involved, the script for live websocket price updates is a bit longer than the previous example.

Notice: The “client.disconnect()” line should be called after you are done collecting data through the websocket. Running this script as-is will result in the websocket disconnecting right after connecting, so remove that line before running the script.

This script was more involved, but not by much. In the following examples, we will continue with data scripts that will collect live order books. An order book provides the exact orders that are available on the exchange.

Order books are necessary for trading, so these next examples are important to understand.

Getting a snapshot of the live order book

Using the rest endpoints, we can get the latest snapshot of the order book. This is ideal for people who aren’t able to connect to the order book websocket, but still want to trade.

It’s as easy as that!

You can now view the available orders on the exchange.

Getting live order book updates using a websocket

Since the endpoint for order book snapshots would require your trading bot to continuously poll for the latest updates, it might be easier to subscribe to the websocket and continuously update a local copy of the order book.

Each time the order book changes, Shrimpy will immediately send out updates through the websocket. That way you can always be kept up to date.

Notice: The “client.disconnect()” line should be called after you are done collecting data through the websocket. Running this script as-is will result in the websocket disconnecting right after connecting, so remove that line before running the script.

We won’t discuss how to maintain the order book in these examples, so you will need to devise your own strategy for how you maintain the local copy of the order book when using the websocket.

Connect to your exchange account

We’re getting close to trading. Before we can trade, we must connect our exchange account to Shrimpy. Earlier in this tutorial you created an API key on your favorite exchange. This is the time to find where you securely stored those keys.

This script will connect your exchange account to Shrimpy so that your account can be managed through Shrimpy. After this script is run once for your exchange account, you will not need to run it again.

Running this script multiple times will result in the same exchange account being linked multiple times. We don’t want that, so only run this script one time for each exchange account.

Also, you might notice that we created a “User” in this script. We only want to create one “User”, so don’t execute those lines more than once.

You can learn more about users in this detailed article.

Getting exchange account balances

In addition to deciding when to trade and at what price to trade, we also need to know how much we can trade. This is determined by collecting our balance data from the exchange.

Since we previously linked our exchange account to Shrimpy and created a user, we can start retrieving information regarding our account.

There we have it, we now have enough information to start making trades!

Executing a smart market order on the exchange

Before we execute our first trade, remember that these are just examples. Running these examples will result in actual trades being executed on your account. That means you will incur trading fees, potentially lose funds if the asset you buy depreciates in value, and other risks that are associated with trading.

The provided scripts are for example purposes and are not production-grade.

Warning: The following script will sell everything you own on the exchange and buy Bitcoin. If you don’t want this to happen on your account, do not run this script.

Executing trades with smart order routing

The evolution of trading is smart order routing. Rather than simply placing market orders on the exchange to move funds around, Shrimpy provides built-in smart order routing infrastructure.

On-demand smart order routing is a game-changer for the cryptocurrency industry, so the next script will show how simple it is to begin using.

Notice: The only change that was made for the order placement was turning “smart order routing” to “True”.

This script will intelligently route your orders from one asset to another. It’s as simple as that.

That’s all we have for the trading examples. Before we close out these example tutorials, let’s look at how we can collect charting candlesticks.

Collecting candlesticks for charting asset prices

Traders that are deciding when to trade often turn to candlestick charts. These charts provide an overview of how the price of an asset has changed over time. Accessing this data through the Shrimpy APIs is also simple.

In the above example, the chart candlesticks are plotted using the plotly library.

Now that we have access to all these different endpoints and trading options, let’s put everything together for one final example script.

Putting together one final example script

The final script will evaluate the BTC/USDT trading pair and execute a trade when Bitcoin reaches 11,000 USDT.

Reminder: These scripts are for example purposes only. They are not production-grade scripts that should be used in a full application. We must remember to handle edge cases, errors, and failure states. This script does none of those things.

Final Thoughts

We not have enough examples to get started developing our complete trading bot. Use these scripts as reference materials when starting out to get an idea of how to access data and execute trades with the Shrimpy Developer APIs.

Enjoy the simplicity of the APIs and prevent yourself from struggling with integrating infrastructure for every exchange.

Learn more about the APIs on the website Universal Crypto Trading APIs.

--

--

ShrimpyApp
The Dark Side

Shrimpy is a crypto exchange trading bot for portfolio management, indexing the market, rebalancing, and strategy backtesting. Join now at shrimpy.io.