How to Build a Trading Bot

August 2, 2021
9m
Read Time

There is no one way to build a cryptocurrency trading bot. That’s why we find such a varying degree of quality. In the following sections, we will highlight the easiest way to build a robust, high-quality trading bot. 

While it’s possible to build trading bots from the ground up, this is not advisable. Building custom infrastructure to connect to every cryptocurrency exchange can take months to years to develop. Custom update cycles, confusing documentation, and odd functionality can make building a trading bot a nightmare. Not to mention it would require a farm of hundreds of servers just to support a few thousand active traders. 

In this article, we will discuss building a cryptocurrency trading bot by taking advantage of the Universal Crypto Exchange APIs. These APIs connect to every major cryptocurrency exchange without needing to write any custom software. Simply connect to the one universal API and you will instantly be connected to every major exchange for trading, portfolio management, user management, data collection, automated infrastructure scaling, and more. It’s like a universal remote for cryptocurrency trading.

Register a Developer Account

Before we can use the Universal Crypto Exchange API, we need to register for a developer account. Follow the link here to sign up

Generate Master API Keys

Once we’ve created an account, our next step is to create a new API master key. This master key will be used to manage all our users, requests for creating new users, and can also execute trades. 

Navigate to the “API Keys” page and select to “Create Api Master Key”. This will walk you through the process of generating the keys. There will be a number of steps that will require your verification as well as enabling additional security precautions like 2FA. It’s nothing fancy like KYC, just basic email and account verification.

Once complete, you will be presented with a public and private (secret) API key. These keys must be securely stored and never sent to anyone. They will be used to manage users, make trades on behalf of users, and much more. These are only for your use. If you wish to allow users to directly access their accounts, link exchanges, and trade, this can be done by generating user-specific API keys via the master API keys. We will discuss how to do this a little bit later.

Note: The secret key will only be shown one time. Once you have selected to “Show” the key, you will never again be able to recover this secret key if it is not stored securely outside the application. If lost, you must create a new set of API keys. 

There are a few settings we need to configure before we can dive into using our master developer API keys.

User - Checking this box will allow this API key to create and manage users of your application. 

Account - Checking this box will allow this master API key to connect exchange accounts on behalf of your users and also collect data from the exchange regarding your users. 

Trade - Checking this box will allow this key to execute trades on behalf of your users. 

These settings are separated out so you have the freedom to decide what role these API keys will play in your process. For example, if you only want to be able to create users, but then the users will manage their connecting of exchange accounts and trading individually, all you would need is the ability to create and manage users. 

In addition to selecting the permissions to enable this master API key, don’t forget to whitelist the IPs which will be sending requests with these API keys. This should be the servers that will hold these API keys so only that server can send requests for you. Any requests from other IPs will fail. This security feature ensures that if your keys were ever stolen, the hacker would not be able to use the API keys. 

Let’s take a closer look at the settings that are a part of each of these permissions.

User - Endpoint Overview

The following section will discuss the endpoints which fall under the “User” permission setting. If you have enabled “User” permissions on the API keys, these are just a few of the endpoints which you will be able to access. 

Create Users

The first thing we must do before we can start trading on an exchange, collect data for an exchange account, or execute our strategy is create a user. Each user you create is intended to represent one real-world person who is using the trading bot.

Let’s take a look at how we create a user.

Request

POST https://dev-api.shrimpy.io/v1/users

Request Body (optional)

{

   "name": "customnameforthisuser"

}

Once you request the creation of a new user, you will receive a new unique identifier for this user. This should be stored such that it’s easy to map each user in your application to the user ID in the developer APIs. 

Response:

{

   "id": "701e0d16-1e9e-42c9-b6a1-4cada1f395b8"

}

Generate User Specific API Key

Once we’ve generated the user, we can also generate user-specific API keys. The purpose of these user API keys is to allow each individual user to communicate with the API servers, distributing the request load so your servers don’t need to handle every request. If you’re building a mobile application, this means most requests can be sent directly to the APIs where a direct line of communication will be maintained to collect data, execute trades, link exchange accounts, and more.


Request

POST https://dev-api.shrimpy.io/v1/users/701e0d16-1e9e-42c9-b6a1-4cada1f395b8/keys

Response:

{

   "publicKey": "51ac18b7d208f59b3c88acbb1ecefe6ba6be6ea4edc07e7a2450307ddc27ab80",

   "privateKey": "85c977ef4070f1deee70192ba7fd5a6caf534f891e4918cfffec11cd6b625e77db4f80347cb436bcaa8882231bacb02f0798a696f101fdd1ef268d66fc63c213"

}

These API keys can be sent to the user for which they are associated. That way the user can manage their own exchange accounts. 

Account - Endpoint Overview

The following endpoints will be managed by the “Account” permission setting. Enabling the “Account” permissions on the API keys allow you to use the following, and more, endpoints. 

Connect Exchange Account

The next step to implementing our trading solution is to link exchange accounts. This can either be done by the master keys or can be managed by each individual user by utilizing the user API keys. 

Request

POST https://dev-api.shrimpy.io/v1/users/701e0d16-1e9e-42c9-b6a1-4cada1f395b8/accounts

Request Body

{

   "exchange": "binance",

   "publicKey": "GOelL5FT6TklPxAzICIQK25aqct52T2lHoKvtcwsFla5sbVXmeePqVJaoXmXI6Qd",

   "privateKey": "SelUuFq1sF2zGd97Lmfbb4ghITeziKo9IvM5NltjEdffatRN1N5vfHXIU6dsqRQw",

}

The “publicKey” and the “privateKey” included here are the exchange API keys that are created on the exchange by the user. These are not the user API keys we received from the Universal Crypto Exchange APIs in the previous steps. 

Response

{

   "id": 1234

}

Once the account is successfully contacted by the API servers, an “id” will be returned. This can be stored for later accessing of this individual exchange account.

Access Account Asset Balances

Since the exchange account has been successfully linked, we can now collect data from the exchange account. The following endpoint would retrieve the asset balances for the linked exchange account. 

Request

GET https://dev-api.shrimpy.io/v1/users/701e0d16-1e9e-42c9-b6a1-4cada1f395b8/accounts/123/balance

Response

{

 "retrievedAt": "2019-01-09T19:17:33.000Z",

 "balances": [

   {

     "symbol": "KCS",

     "nativeValue": 2306,

     "btcValue": 0.33486579,

     "usdValue": 1327.8775274784

   },

   {

     "symbol": "ETH",

     "nativeValue": 4.0e-8,

     "btcValue": 1.4960564e-9,

     "usdValue": 5.9324652822859e-6

   }

 ]

}

Trade - Endpoint Overview

The following settings are managed by the “Trade” permission settings. Enabling the “Trade” permissions on the API keys allow you to use the following, and more, endpoints. 

Smart Order Routing

Smart order routing is a convenience feature that automatically optimizes trading across asset pairs in order to receive the best order execution. This drastically simplifies the integration process for smart order routing strategies and can save on execution costs. 

Request

POST https://dev-api.shrimpy.io/v1/users/701e0d16-1e9e-42c9-b6a1-4cada1f395b8/accounts/123/trades

Request Body

{

   "fromSymbol": "BTC",

   "toSymbol": "ETH",

   "amount": "0.01",

   "smartRouting": true,

}

Once the order is placed, it will automatically be routed across all available trading pairs to optimize for the outcome. 

Response:

{

   "id": "72dff099-54c0-4a32-b046-5c19d4f55758"

}

Place a Limit Order

Some applications require fine control over the order book. These applications can implement these advanced strategies by executing limit orders via the unified limit order trading endpoints. 

Request

POST https://dev-api.shrimpy.io/v1/users/701e0d16-1e9e-42c9-b6a1-4cada1f395b8/accounts/123/orders

Request Body

{

   "baseSymbol": "ETH",

   "quoteSymbol": "BTC",

   "amount": "0.5",

   "price": "0.0344",

   "side": "BUY",

   "timeInForce": "IOC"

}

Response:

{

   "id": "72dff099-54c0-4a32-b046-5c19d4f55758"

}

The Universal Crypto Exchange APIs support “Immediate or Cancel” (IOC) and “Good ‘Til Canceled” (GTC) orders. Both of these order types are implemented using the same request structure, so your trading bot can conveniently switch between placing the different types of orders without trouble.

Allocate a Portfolio

Besides the convenience of the smart order routing, there are additional endpoints designed for portfolio strategies. These endpoints can be used for allocating portfolios, rebalancing, or implementing a complete portfolio strategy. One of these endpoints is the ability to quickly allocate a diverse portfolio.

Request

POST https://dev-api.shrimpy.io/v1/users/701e0d16-1e9e-42c9-b6a1-4cada1f395b8/accounts/123/allocate

Request Body

{

   "isDynamic": false,

   "allocations": [

       {

           "symbol": "USDT",

           "percent": "100"

       }

   ]

}

Response:

{

   "success": true

}

With a single call, your trading bot is able to send the percentages of each asset you would like to have in the portfolio and the Universal Crypto Exchange APIs will intelligently construct that portfolio. There is no additional work required. 

Public Data (No Permissions Required)

Public data is accessible to all users. This means it does not fall under any of the permission settings that are enabled or disabled on the master API key. 

Exchange Assets

Each exchange has different assets available, so it’s important to know which exchange supports which assets. This endpoint will return the different assets available on each exchange along with their symbol and name. 

Request

GET https://dev-api.shrimpy.io/v1/exchanges/bittrex/assets

Response

[

 {

   "id": 38,

   "name": "Bitcoin",

   "symbol": "BTC",

   "tradingSymbol": "BTC"

 },

 {

   "id": 229,

   "name": "Litecoin",

   "symbol": "LTC",

   "tradingSymbol": "LTC"

 },

 ...

]

Collect Full Depth Order Book

To place specific orders on the order book, developers need access to full depth order book data in real-time. This data can be accessed through simple endpoints that return market data in real-time. Experiment with collecting this data by sending requests to the API calls detailed below.

Request

GET https://dev-api.shrimpy.io/v1/orderbooks?exchange=bittrex&baseSymbol=XLM&quoteSymbol=BTC&limit=10

Response

[{

 "baseSymbol": "XLM",

 "quoteSymbol": "BTC",

 "exchanges": [{

   "exchange": "Bittrex",

   "orderBook": {

     "asks": [

       {

         "price": "0.00002585",

         "quantity": "1891.1316431"

       },

       {

         "price": "0.00002594",

         "quantity": "35200"

       },

       ...

     ],

     "bids": [

       {

         "price": "0.00002577",

         "quantity": "774.92250177"

       },

       {

         "price": "0.00002576",

         "quantity": "3509.07031022"

       },

       ...

     ]

   }

 }]

}]

Candle Stick Trading Data

Another convenience feature is the ability to collect candle stick OHLCV charting data through these unified APIs. This candlestick data can be used to display charts for users who are active traders.

Request

GET https://dev-api.shrimpy.io/v1/exchanges/coinbasepro/candles?quoteTradingSymbol=BTC&baseTradingSymbol=XLM&interval=1H 

Response

[

 {

   "open": "0.0000157300000000",

   "high": "0.0000157800000000",

   "low": "0.0000155800000000",

   "close": "0.0000157100000000",

   "volume": "219444.0000000000000000",

   "quoteVolume": 3.44176145,

   "btcVolume": 3.44176145,

   "usdVolume": 27437.297915762,

   "time": "2019-05-24T23:00:00.000Z"

 },

 {

   "open": "0.0000157100000000",

   "high": "0.0000157500000000",

   "low": "0.0000156900000000",

   "close": "0.0000157300000000",

   "volume": "1603.0000000000000000",

   "quoteVolume": 0.02520959,

   "btcVolume": 0.02520959,

   "usdVolume": 201.98615317277,

   "time": "2019-05-25T00:00:00.000Z"

 },

 ...

]

User Request Flow

Now that we have an understanding of the different endpoints that are available through these APIs, let’s revisit the user request flows that were discussed earlier in this article. In order to prevent every request from being managed by a centralized server, we should distribute the requests to originate from the users. This lightens the request burden, so we can stay lean and agile. A detailed discussion on the optimal user request flows can be found in one of our previous articles here.

This illustration highlights how the initial user creation can be managed by a centralized server while the individual user requests can come from each individual user. This prevents unnecessary routing by a centralized server between the user and the Universal Crypto Exchange APIs. 

Course Roadmap
Course Roadmap
Course Roadmap
Course Roadmap
Good work! You've reached the end of the course! 
More Courses