HOW TO CREATE A CRYPTO TRADING BOT

How to create a Crypto Trading Bot.

Trading cryptocurrency can feel overwhelming in the beginning. There are a lot of components to think about, data to collect, exchanges to integrate, and complex order management.

Why Trading Bots?

We want a system that is systematic, emotionless, and works 24/7.

Unlike humans, trading bots can consistently execute strategies that are precise. An example of a precise strategy that is difficult for humans to implement is arbitrage. Arbitrage trading is a strategy that is almost exclusively executed by trading bots in the world today. Trading bots can execute orders within milliseconds of an event occurring. Humans don’t have the reflexes or capacity to effectively implement such a strategy without some sort of trading bot.

More generally than simply what is possible, traders want something that is reliable and deterministic. That way there is no opportunity for error. When the strategy is set, the strategy will be executed based on the parameters of the algorithm. That’s really all there is to it.

Setup

Before we can begin, we must set up our environment. This will involve a few steps to get access to trading APIs and our exchange accounts, but once set up, we won’t need to make any changes to our development environment.

Sign up for Shrimpy

Go to the Shrimpy Developer API website here. Sign up for an account.

Generate & Store API Keys

Before we can start using the Shrimpy APIs, we will need to generate our API keys. This can be done by logging into your Shrimpy Developer account and going to the “API Keys” tab. Select the button to “Create Api Master Key”.

Select “Create Api Master Key”.

Once you select the “Create Api Master Key” button, you will be prompted to verify your account by entering your password and 6 digit 2FA. If you have not yet enabled 2FA for your account, you will first need to go through the process of setting up 2FA.

Enter your 6-digit verification code and account password.

Once you have verified your account, Shrimpy will send you an email that will require you to confirm the creation of the API key.

Confirm your email by clicking on the link in the verification email.

After confirming the creation of the API key in your email, you can then see a card that represents your developer API key. The public key will be displayed by default.

Select to “Show” the private API key. This can only be done one time, so securely store the secret key once it has been shown.

Select to “Show” the private key. The private key will not be shown by default and can only be viewed ONE time. That means after you view your private key, Shrimpy will never show you the key again. If you don’t securely store the private key, you will need to go through the process of creating a new key. Once you select to “Show” the private API key, you will be prompted again to confirm your account by entering your 2FA code and password.

Copy both the public and private (secret) keys to secure locations.

Once the private API key has been shown, copy both the public and private API keys to a secure location. Do not ever share this API key with anyone.

Before we are done with the API key setup, select to enable all of the permissions on the API key. We will use all of the settings for this tutorial guide, however, you can reconfigure your setup once you are ready to deploy your production version of your trading bot. During testing, we won’t require any complex setup.

Note: You can create multiple API keys. If you want to have one set of API keys with only “Data” permissions, one set with only “Account” permissions, and one with “User” permissions, you are welcome to set up your keys any way you want.

Enable all of the permissions on the API keys and select “Update”.

We don’t need to buy any credits to test Shrimpy, but you can purchase credits at any time on the “Payment” tab. This will look something like the screenshot below.

Purchase credits when ready. Shrimpy will start you off with 500 free credits, so this tutorial won’t require any payment.

Before credits can be purchased, we first require you to link a payment method. After linking a payment method, you can enter the value of the credits you wish to purchase.

Once you’ve gone through all these steps, you can log out of your Shrimpy Developer API account. We won’t need anything else from our account at this time.

Setting Up Our Python Environment

There are a few things we will need to set up for our Python environment before we can start coding. First, start by installing the Shrimpy Python Library.

pip install shrimpy-python

Besides installing the Shrimpy Library, we will also install a few other libraries that will be used for plotting data later in the tutorial. These libraries are Pandas and Plotly.

pip install pandas
pip install plotly==4.1.0

Note: The Shrimpy Python Library is designed to work with Python3. If you are using Python2, please update your version of Python.

Exchange API Keys

Before we can start coding, there is one more piece of information we will need. That is the exchange API keys. These API keys are retrieved from the exchange that you want to use for trading.

With the Shrimpy personal plan, you can connect to 20 different exchange accounts at one time, but for these examples, we will only connect to one. Log into your exchange account and follow the appropriate tutorial in our list of exchange specific articles here.

These articles will help you get access to your API key and copy them into a secure location. Once the API keys have been copied, you can close out of the article. You do not need to paste them into the Shrimpy portfolio management application since we will only use them for our scripts throughout these example tutorials.

Code

We’re now ready to start coding! The following examples will include blanks where you will need to input your public and secret API keys for both Shrimpy and the exchange.

When you see:

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

Input the Shrimpy API Master keys you generated in previous steps.

When you see:

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

Input the exchange specific API keys you generated in previous steps.

Collecting Pricing Data

One of the most important pieces of information for a bot to decide when to execute a trade is pricing data. Exchange specific pricing data should be used to calculate the optimal trade times, as well as the exact placement of the orders.

Generally, order book data is used to make the specific decisions on where to place an order and trade data can be used to determine when an order should be executed.

Simple Price Ticker

The simple price ticker is a way to access the latest prices for each asset on an exchange. This value is updated on a 1-minute interval. The purpose of this endpoint is for display purposes only. This endpoint is not designed for order execution or arbitrage. We provide other endpoints for those purposes.

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

Websocket Price Ticker

If you need a real-time price ticker with the latest trades being executed, this websocket price ticker is for you. Unlike the “Simple Price Ticker” the websocket price ticker is real-time. That means there is no delay between the time the trade is executed on the exchange and this price ticker updates.

This endpoint is more complex, however, as it will require a websocket connection.

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

Simple Live Order Book Snapshot

This rest API endpoint will provide the latest snapshot of the live order book. As the order book is updated live, you can access a snapshot of this live data to either execute trades, provide information for decision making, or even just analyze the market.

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
)

Websocket Live Order Book

If you don’t want to poll for updates to get the latest order book data, you can always use the live order book websocket, similar to the live websocket for trades.

The order book websocket will immediately send the latest order book updates as soon as any changes are made to the exchange’s order book. That way your local copy of the order book is never outdated.

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

Linking an Exchange Account

Before we can begin accessing our account information from the exchange or execute trades, we will need to link an exchange account. We only need to connect an exchange account one time. After the account has been linked, Shrimpy will maintain the connection so you don’t need to re-link the keys 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']

Retrieving Exchange Account Balances

To trade, it’s likely we will want to know how much of each asset we have available in our account to trade. Without this information, we would be guessing at the quantity of funds we have available for each asset.

Use this script to access the balances for any exchange account that has been linked to your Shrimpy Developer APIs.

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
)

Executing a Trade

Now that we have the price data, order book data, and account information we need, it’s time to start trading!

It is important to remember that trading is complex. The examples provided here will be a great starting point, but they are not the finish line. Developing a complete trade placement and execution algorithm will take time.

Simple Trade

Create a trade by first accessing the available balances on the exchange you have connected to Shrimpy. In this example, we will execute trades in order to consolidate all of our funds into BTC.

Running this script will execute live trades on your real exchange account. That means you should only run this script if you are intending to move all of your asset holdings into BTC.

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
)

Smart Order Routing

Smart order routing will intelligently route the trades through any available trading pairs in order to receive the best price. When executing a smart order routing strategy, you cannot specify the quote currencies, only the “from” and “to” currencies. The quote currencies will be determined based on the paths that will result in the best order execution.

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
)

Charting Candlesticks

If you’re trading, you will want to have a visual way to see the current price of the assets. This is typically done through candlesticks. In this example, we will show you how to generate candlesticks for viewing or strategy integration.

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

Putting It All Together

Now that you have each component for building your trading bot. It’s time to put each of those components together to execute a trading bot strategy.

For example, if you want to build a simple script that will look at the BTC/USDT pair and trade all of your BTC to USDT as soon as BTC touches 10000 USDT, you can do something like this.

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) > 10000:
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)

This script will monitor the market until Bitcoin hits 10000 USDT. At that point, it will trade all of your BTC to USDT.

This example doesn’t check any edge cases, failure modes, and many other situations that will arise. None of the examples provided are suitable for production. They are for educational purposes only to provide a way to get familiar with the concepts to build a trading bot.