Arbitrage Scripts for Crypto Trading Bots

earth-2254769_960_720.jpg

The volatility of the cryptocurrency market makes it an attractive venue for arbitrage trading. However, the difficulty of building arbitrage infrastructure makes it a cumbersome process.

Linking to multiple exchanges, accessing real-time websockets, and executing the arbitrage strategy all require connectivity to multiple exchanges. Each exchange is different in the way they provide their APIs, which prevents simple integrations.

In this article, you will be provided with a script to automatically connect to any of the most popular exchanges in the crypto market. With these connections, you will have access to live pricing streams which will allow us to build the beginnings of an arbitrage strategy.

While we won’t cover order execution in this article, once the opportunity is identified, executing a trade is simple.

You can find tutorials on how to execute trades, collect portfolio balance information, and more in our recent blog posts here:

Let’s not wait any longer - It’s time to arbitrage!

What is arbitrage?

We won’t cover the details of arbitrage in this article. To learn more about what is arbitrage, visit our previous article here.

Setup

Diving right into the script, let’s start by setting up our environment.

Install Libraries

Everything we need is provided by the Shrimpy developer API library. To install the python library, run the following command:

pip install shrimpy-python

Get API Keys

Once the library has been installed, we will need to sign up for a Shrimpy Developer API account to get our API keys.

After signing up, generate your Master API Keys by selecting the button to generate new API keys. After these keys have been created, make sure to enable the “Data” permission on the keys, otherwise we won’t be able to access the websockets in later steps. If you want to trade with those keys, you should enable ALL permissions on the keys.

Save your keys for later steps.

Note: In order to access the real-time websockets, we recommend subscribing to our “personal” subscription plan. This will give you near unlimited access to websockets, while still having the ability to execute trades, build your strategies, and collect data.

Get Coding

The setup is now done, so let’s get coding!

Imports

Start off by importing the Shrimpy library. This will be the only library we will need to import for this script tutorial.

import shrimpy

Define Your Message Handlers

When a message is received through the websocket, we will need a handler which will determine how the data will be processed.

Before get get to the fun websocket message processing, let’s create a handler which will manage the errors which come back through the websocket. This will simplify the way we manage our errors.

def error_handler(err):
    print(err)

Next, it’s time to create our core message handler. This handler will receive the websocket updates and then process them. Since we haven’t walked through the entire script yet, each of these values may not make sense, but here is an example handler.

exchanges_bbo = {}

def handler(msg):
    bid_price = msg['content']['bids'][0]['price']
    ask_price = msg['content']['asks'][0]['price']
    exchanges_bbo[msg['exchange']] = {'bid': float(bid_price), 'ask': float(ask_price)}
    best_bid = 0.0
    best_ask = 10000000.0
    best_bid_exchange = ''
    best_ask_exchange = ''
    for key, value in exchanges_bbo.items():
        if value['bid'] > best_bid:
            best_bid = value['bid']
            best_bid_exchange = key
        if value['ask'] < best_ask:
            best_ask = value['ask']
            best_ask_exchange = key
    if best_bid > best_ask:
        print("sell on " + best_bid_exchange + " for " + str(best_bid))
        print("buy on " + best_ask_exchange + " for " + str(best_ask))
    else:
        print("No Arbitrage Available")

While it feels like a lot, all this handler is doing is collecting the updates from the websocket, storing the best bid and ask price for each exchange, then comparing the prices across exchanges to see if there are any arbitrage opportunities for that trading pair.

“exchanges_bbo” is where we store the best bid and ask price for each exchange. When we get each tick message from the websocket, the values in that dictionary are updated to include the latest prices for each exchange.

If the best bid is greater than the best ask, that means there is an arbitrage opportunity. When this happens, the script will print out which exchange you should sell on and which exchange you should buy.

Note: You can do whatever you want in the handler. This is just an example. The easiest handler would be to simply print out each message as they come in, similar to the error handler. A more complex handler would go a step further and execute the trades based on the arbitrage opportunities.

Client Creation

In the steps before, we created our developer API keys for the Shrimpy APIs. These keys can now be assigned to variables for the public and private keys.

public_key = '6d73c2464a71b94a81aa7b13d...'
private_key = 'e6238b0de3cdf19c7861f8e8f5d137ce7113ac1e884b191a14bbb2...'

api_client = shrimpy.ShrimpyApiClient(public_key, private_key)
raw_token = api_client.get_token()
client = shrimpy.ShrimpyWsClient(error_handler, raw_token['token'])

To create the rest client, we need to pass in the public and private keys. This client is then used to request a token for the websocket client.

Once the token is received, simply pass it into the constructor for the websocket client to create the websocket client.

Connect

Before subscribing to specific websocket channels for each trading pair, go ahead and connect to the websocket stream. This will require the use of the one time token you retrieved from the previous step. If you need to create another client for whatever reason, you will need to once again get a token and pass it into the client constructor.

client.connect()

Note: Tokens can only be used ONE TIME. Once the client is created using the token, you will need to request a new token each time you create a new client. You DO NOT need to request a token in order to subscribe to websocket channels. Only for the client connection.

Subscribe

Now that we are connected to the websocket, we can subscribe to each of the exchange pairs we want to use for our arbitrage script. This can easily be done in the following way.

exchanges = ["bittrex", "binance", "kucoin"]
pair = "btc-usdt"

for exchange in exchanges:
    subscribe_data = {
        "type": "subscribe",
        "exchange": exchange,
        "pair": pair,
        "channel": "bbo"
    }
    client.subscribe(subscribe_data, handler)

This will subscribe to the BTC-USDT pair for Bittrex, Binance, and KuCoin. Upon each tick, we will be able to tell if there are any arbitrage opportunities across these exchanges for this asset pair.

Note: Shrimpy API’s allow for 100 websocket subscriptions per client and up to 10 clients per IP. That means you can subscribe to up to 1,000 trading pairs across the 17+ different exchanges we support.

Disconnect

After you’re done collecting data, you can disconnect using the following simple command.

client.disconnect()

That’s it! Everything you need to know to get started building your arbitrage data stream.

Arbitrage bot identifying trades.png

Everything In One Script

Now that we’ve broken down the script step by step, let’s look at the entire masterpiece. What it looks like as a single script that we can run.

# import the Shrimpy library for crypto exchange websockets
import shrimpy

# a sample error handler, it simply prints the incoming error
def error_handler(err):
    print(err)

exchanges_bbo = {}

# define the handler to manage the output stream
def handler(msg):
    bid_price = msg['content']['bids'][0]['price']
    ask_price = msg['content']['asks'][0]['price']
    exchanges_bbo[msg['exchange']] = {'bid': float(bid_price), 'ask': float(ask_price)}
    best_bid = 0.0
    best_ask = 100000.0
    best_bid_exchange = ''
    best_ask_exchange = ''
    for key, value in exchanges_bbo.items():
        if value['bid'] > best_bid:
            best_bid = value['bid']
            best_bid_exchange = key
        if value['ask'] < best_ask:
            best_ask = value['ask']
            best_ask_exchange = key
    if best_bid > best_ask:
        print("sell on " + best_bid_exchange + " for " + str(best_bid))
        print("buy on " + best_ask_exchange + " for " + str(best_ask))
    else:
        print("No Arbitrage Available")


# input your Shrimpy public and private key
public_key = '6d73c2464a71b94a81aa7b13d...'
private_key = 'e6238b0de3cdf19c7861f8e8f5d137ce7113ac1e884b191a14bbb2...'

# create the Shrimpy websocket client
api_client = shrimpy.ShrimpyApiClient(public_key, private_key)
raw_token = api_client.get_token()
client = shrimpy.ShrimpyWsClient(error_handler, raw_token['token'])

# connect to the Shrimpy websocket and subscribe
client.connect()

# select exchanges to arbitrage
exchanges = ["bittrex", "binance", "kucoin"]
pair = "btc-usdt"

# subscribe to the websockets for the given pair on each exchange
for exchange in exchanges:
    subscribe_data = {
        "type": "subscribe",
        "exchange": exchange,
        "pair": pair,
        "channel": "bbo"
    }
    client.subscribe(subscribe_data, handler)

Running this script will immediately start printing out the arbitrage opportunities for this asset pair on the specified exchanges.

To expand on the functionality of this script, some options for next steps would be to evaluate how to place orders on the exchange, taking advantage of these opportunities by trading.

Purpose

The purpose of this article isn’t to build an entire robust arbitrage trading algorithm for you. It’s to show you the beginnings of something which you can expand and grow. There is a lot of room for improvement.

In a few minutes, it’s possible to whip up amazing features using the Shrimpy developer APIs. Instead of spending hours fiddling with exchange APIs, you can get consistent behavior across every major exchange by developing with the Universal Crypto Trading APIs.

Trading Bots for Cryptocurrency

Developers can use these simple scripts as the foundation for cryptocurrency arbitrage bots. By selecting the assets to arbitrage, instantly uncover market opportunities.

It can’t get any easier.

Shrimpy integrates 17+ different exchanges which makes the development process seamless across every exchange. No unique behaviors or odd errors. The consistency is built into the platform.

Learn more about everything Shrimpy offers by joining our Telegram.

To access the complete Python and Node libraries, follow these links:

Node

Python

Check out some of our latest video tutorials on how to build a crypto trading bot!

Don’t hesitate to reach out if you want to share with our team what you’re building!


About Shrimpy

Shrimpy leads the market as the premier portfolio management application. Users are able to configure a custom crypto portfolio and implement a passive rebalancing strategy, removing the hassle of having to actively trade crypto.

Shrimpy Web Application: Shrimpy - Cryptocurrency Portfolio Management

Shrimpy’s Developer Trading API is a unified way to integrating trading functionality across every major exchange. Collect historical market data, access real-time websockets, execute advanced trading strategies, and manage an unlimited number of users.

Shrimpy Crypto Trading API: Shrimpy | Crypto Trading APIs for Developers

Don’t forget to follow us on Twitter and Facebook for updates, and ask any questions to our amazing, active community on Telegram.

The Shrimpy Team