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?

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

Sign up for Shrimpy

Generate & Store API Keys

Select “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.

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.

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 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.

Crypto Trading Bot

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.

Crypto Trading Bot

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

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

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

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

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

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

Websocket Price Ticker

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

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

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

# 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

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

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

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

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

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

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store