Monday, January 25, 2021
Home The Capital Building Crypto Trading Bots with Python

Building Crypto Trading Bots with Python

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.

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.

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.

pip install shrimpy-python

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.

pip install pandas
pip install plotly==4.1.0

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.

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.

shrimpy_public_key = '...'
shrimpy_secret_key = '...'

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.

exchange_public_key = '...'
exchange_secret_key = '...'

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.

import shrimpyshrimpy_public_key = '...'
shrimpy_secret_key = '...'
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)ticker = client.get_ticker('binance')

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.

import shrimpyshrimpy_public_key = '...'
shrimpy_secret_key = '...'
# This is a sample handler, it simply prints the incoming message to the console
def error_handler(err):
print(err)
# This is a sample handler, it simply prints the incoming message to the console
def handler(msg):
print(msg['content'][0]['price'])
api_client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)
raw_token = api_client.get_token()
client = shrimpy.ShrimpyWsClient(error_handler, raw_token['token'])
subscribe_data = {
"type": "subscribe",
"exchange": "binance",
"pair": "ltc-btc",
"channel": "trade"
}
# Start processing the Shrimpy websocket stream!
client.connect()
client.subscribe(subscribe_data, handler)
# Once complete, stop the client
client.disconnect()

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.

import shrimpyshrimpy_public_key = '...'
shrimpy_secret_key = '...'
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)orderbooks = client.get_orderbooks(
'bittrex', # exchange
'XLM', # base_symbol
'BTC', # quote_symbol
10 # limit
)

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.

import shrimpyshrimpy_public_key = '...'
shrimpy_secret_key = '...'
# This is a sample handler, it simply prints the incoming message to the console
def error_handler(err):
print(err)
# This is a sample handler, it simply prints the incoming message to the console
def handler(msg):
print(msg)
api_client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)
raw_token = api_client.get_token()
ws_client = shrimpy.ShrimpyWsClient(error_handler, raw_token['token'])
subscribe_data = {
"type": "subscribe",
"exchange": "binance",
"pair": "eth-btc",
"channel": "orderbook"
}
# Start processing the Shrimpy websocket stream!
ws_client.connect()
ws_client.subscribe(subscribe_data, handler)
# Once complete, stop the client
ws_client.disconnect()

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.

# import required libraries
import shrimpy
# assign your Shrimpy Master API keys for later use
shrimpy_public_key = '...'
shrimpy_secret_key = '...'
# assign your exchange keys for which you wish to access the balance data
exchange_name = "bittrex"
exchange_public_key = '...'
exchange_secret_key = '...'
# create the Shrimpy client
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)
# create a user which will be linked to our exchange
create_user_response = client.create_user('The Shrimp Master')
user_id = create_user_response['id']
# link our first exchange so we can access balance data
link_account_response = client.link_account(
user_id,
exchange_name,
exchange_public_key,
exchange_secret_key
)
account_id = link_account_response['id']

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.

import shrimpy# use your Shrimpy API public and private keys to create the client
shrimpy_public_key = '...'
shrimpy_secret_key = '...'
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)# note: since we created a user in our last example script,
# we can just retrieve our list of users.
users = client.list_users()
first_user_id = users[0]['id']
# retrieve the accounts associated with this user
accounts = client.list_accounts(
first_user_id
)
first_account_id = accounts[0]['id']
# access balance data for the user account you previously created
balance = client.get_balance(
first_user_id, # user_id
first_account_id # account_id
)

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.

import shrimpy# use your Shrimpy API public and private keys to create the client
shrimpy_public_key = '...'
shrimpy_secret_key = '...'
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)# note: since we created a user in our last example script,
# we can just retrieve our list of users.
users = client.list_users()
first_user_id = users[0]['id']
# retrieve the accounts associated with this user
accounts = client.list_accounts(
first_user_id
)
first_account_id = accounts[0]['id']
# access balance data for the user account you previously created
balance = client.get_balance(
first_user_id, # user_id
first_account_id # account_id
)
holdings = balance['balances']# select the asset for which you would like to consolidate
consolidation_symbol = 'BTC'
# sell every asset besides the consolidation asset
for asset in holdings:
asset_symbol = asset['symbol']
asset_amount = asset['nativeValue']
if asset_symbol != consolidation_symbol:
print('Selling ' + str(asset_amount) + ' of ' + asset_symbol)
create_trade_response = client.create_trade(
first_user_id,
first_account_id,
asset_symbol,
consolidation_symbol,
asset_amount
)

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.

import shrimpy# use your Shrimpy API public and private keys to create the client
shrimpy_public_key = '...'
shrimpy_secret_key = '...'
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)# note: since we created a user in our last example script,
# we can just retrieve our list of users.
users = client.list_users()
first_user_id = users[0]['id']
# retrieve the accounts associated with this user
accounts = client.list_accounts(
first_user_id
)
first_account_id = accounts[0]['id']
# access balance data for the user account you previously created
balance = client.get_balance(
first_user_id, # user_id
first_account_id # account_id
)
# execute a market order
smart_order_response = client.create_trade(
first_user_id, # user_id
first_account_id, # account_id
'BTC', # from_symbol
'ETH', # to_symbol
'0.01' # amount of from_symbol
True # enable smart_routing
)

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

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.

import shrimpy
import plotly.graph_objects as go
# sign up for the Shrimpy Developer APIs for your free API keys
shrimpy_public_key = '...'
shrimpy_secret_key = '...'
# collect the historical candlestick data
client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)
candles = client.get_candles(
'bittrex', # exchange
'XRP', # base_trading_symbol
'BTC', # quote_trading_symbol
'1d' # interval
)
dates = []
open_data = []
high_data = []
low_data = []
close_data = []
# format the data to match the plotting library
for candle in candles:
dates.append(candle['time'])
open_data.append(candle['open'])
high_data.append(candle['high'])
low_data.append(candle['low'])
close_data.append(candle['close'])
# plot the candlesticks
fig = go.Figure(data=[go.Candlestick(x=dates,
open=open_data, high=high_data,
low=low_data, close=close_data)])
fig.show()

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.

import shrimpy
import time
shrimpy_public_key = '...'
shrimpy_secret_key = '...'
# assign your exchange keys for which you wish to access the balance data
exchange_name = "bittrex"
exchange_public_key = '...'
exchange_secret_key = '...'
api_client = shrimpy.ShrimpyApiClient(shrimpy_public_key, shrimpy_secret_key)
raw_token = api_client.get_token()
ws_client = shrimpy.ShrimpyWsClient(error_handler, raw_token['token'])
# create a user which will be linked to our exchange
# skip this step if you've already created a user
create_user_response = api_client.create_user('The Shrimp Master')
user_id = create_user_response['id']
# link our first exchange so we can access balance data
# skip this step if you've already linked an account
link_account_response = api_client.link_account(
user_id,
exchange_name,
exchange_public_key,
exchange_secret_key
)
account_id = link_account_response['id']# wait while Shrimpy collects data for the exchange account
# only required the first time linking
time.sleep(5)
# access balance data for the user account you previously created
balance = api_client.get_balance(
user_id, # user_id
account_id # account_id
)
btcAmount = 0for asset in balance['balances']:
if asset['symbol'] = 'BTC':
btcAmount = asset['nativeValue']
# This is a sample handler, it simply prints the incoming message to the console
def error_handler(err):
print(err)
# This is a sample handler, it simply prints the incoming message to the console
def handler(msg):
price = msg['content'][0]['price']
if int(price) > 11000:
smart_order_response = api_client.create_trade(
user_id, # user_id
account_id, # account_id
'BTC', # from_symbol
'USDT', # to_symbol
btcAmount # amount of from_symbol
True # enable smart_routing
)
subscribe_data = {
"type": "subscribe",
"exchange": "binance",
"pair": "btc-usdt",
"channel": "trade"
}
# Start processing the Shrimpy websocket stream!
ws_client.connect()
ws_client.subscribe(subscribe_data, handler)

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.

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.

Popular Articles