Note: The Shrimpy APIs provides a number of free data endpoints. The paid data endpoints are only for specific historical data, that are not necessary for trading. All the live data endpoints, market endpoints, and charting endpoints will be available to you with this “Personal” plan.

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 shrimpy shrimpy_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 shrimpy shrimpy_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 shrimpy shrimpy_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 shrimpy shrimpy_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 = 0 for 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.

Trading Bot Services

If building a custom trading bot from scratch is not your speed, that’s not a problem! There are some trading bots currently available in the market that you can use. They are ready to onboard new users and start automating your portfolio without any development.