Education

A Guide to Automated Crypto Trading With CEX.IO API Solutions

, March 22, 2022

What is an API?

An application programming interface (API) is a digital bridge that allows two computer programs to interact with each other. The bridge consists of a set of instructions written in a particular computer programming language. It oversees how the two programs can interact with each other, including but not limited to, the language that must be used, the syntax of exchanged messages, and the allowed frequency of messages per second.  

An API allows developers and traders to import an existing platform into their applications to enhance their application’s functionality. This saves a lot of time and resources as developers do not need to build a similar platform from scratch.

Put simply, an API is an algorithmic messenger that takes requests from an application and tells another application what to do. 

What is a Crypto Trading API? 

APIs are used by corporations and businesses in a spectrum of industries, which has been triggered by the adoption of data-driven decision-making, in addition to the world transitioning to a digital infrastructure. The most common use of APIs is in the financial services industry, specifically in asset management and trading. In recent years, the cryptocurrency industry has also joined the bandwagon. 

A cryptocurrency trading API connects a cryptocurrency exchange to a user’s application interface, which is typically a terminal. With a crypto trading API, a user can send orders to an exchange directly from their terminal and import a plethora of information, such as real-time price, volume, and market liquidity data, along with historical market data. The data can then be used as input in developing different trading algorithms on the exchange.

API traders, over anything, look for simple and effective documentation when looking at exchange APIs. It benefits traders when exchanges create their own clients with pre-built functions for pulling historical exchange data, trading, orderbook data, asset price data, and so on. Multiple time granularities (1 hr, 6 hr, 12 hr, 24 hr, 48hr, etc.) for all data types it can apply to, is also beneficial to those using APIs. 

Connecting to a cryptocurrency exchange via a crypto trading API with strong documentation allows a user to more easily:

  1. obtain real-time market data from the exchange, 
  2. obtain historical market data,
  3. submit trade order requests to the exchange, 
  4. receive information about balances on their exchange account,
  5. deposit or withdraw funds from their account, or move funds between wallets.

Why you need a crypto trading API

You can automate your cryptocurrency trades by using an API, which would save you significant time and effort and thus give you flexibility in your daily life. Automation also allows you to create complex and resilient trading strategies to optimize your trades.

Cryptocurrency markets are open 24/7 and have some of the highest volatility among all asset classes, this makes API trading essential to help you navigate your way in this new asset class. Here is a detailed review of the benefits that you will find when using APIs to trade cryptocurrencies.

  • Removing human emotions and error

Tides can change very quickly in cryptocurrency markets, this can take a toll on your emotions. As a result, most traders are inclined to act on emotions, regardless of their experience level. Emotion in trading is historically known to be a profit-killer in financial markets, so adopting a systematic and unbiased methodology in your crypto trading is essential.

That is where APIs come to the rescue. You can program predetermined conditions into your terminal which will instruct the APIs to execute trades, only when they are triggered. As a result, the negative consequences of human sentiment and irrational thinking are eliminated.

  • Never miss an opportunity

The presence of over 15,000 cryptocurrencies in today’s crypto markets makes it almost a guarantee that you’ll miss out on trading opportunities. APIs can monitor an unlimited number of markets, around the clock, so that you could take advantage of any emerging opportunities. In that sense, APIs serve as a trader’s eyes and ears at all times, so you won’t have any more sleepless nights.

  • Arbitrage opportunities

Arbitrage happens when the price of an asset is different on one exchange from the price of the same asset on another exchange. Arbitrage allows you to buy an asset at a cheaper price on one exchange and sell at a premium on the other exchange. APIs can identify and execute these opportunities automatically on your behalf, no matter how long the price disparity is present.

  • Speed

With APIs, trades are executed instantaneously whenever the predetermined conditions are met. This is especially useful when trading cryptocurrencies considering their general volatility. The window of opportunity in crypto markets can be milliseconds long, which can only be captured using APIs.

  • Trade multiple markets simultaneously

The ability to trade multiple markets at the same time is a key benefit of API trading. It allows traders to place orders across multiple exchanges and markets at the same time. It would be impossible to do this manually. Using APIs, you can buy Bitcoin and Ethereum on different exchanges at the same time.

 

How to set up a crypto trading API on CEX.IO

It’s very simple to set up a crypto trading API on CEX.IO. Follow the four steps below to quickly set up and activate your API on CEX.IO: 

1. Scroll to the profile symbol on the right top corner of your CEX.IO account homepage and click on API in the dropdown menu. 

2. On the next page, select the functions and data streams you want to access with your application terminal. Access permissions on CEX.IO consist of place order, cancel order, account balance, open orders, and open positions

3. Once you select the permissions you need, click on the Generate Key button. You will then see on the below table, next to your user ID, a new API key and a private key to use with that API access. You will need this information when you connect to the CEX.IO exchange from your terminal. 

4. Finally, click on the Activate button on the right side and finish the API setup process for your terminal. You’ll need to confirm this action with your 2FA code.

Before connecting to CEX.IO API channel, you need to provide the following information to CEX.IO:

  • IP address or network range information: If you want to connect to CEX.IO APIs from your terminal, your specific IP address or network information needs to be whitelisted by CEX.IO first. This is so that your terminal will be able to get past the safety firewall.  
  • SSL certificate: CEX.IO only accepts valid SSL certificates to connect to its APIs. SSL adds an extra layer of security to reduce the risk of unauthorized access to these channels. 

API channels on CEX.IO

CEX.IO provides three different API channels for cryptocurrency traders:

  1. WebSocket (WS): Using a WebSocket channel, you can 
  • access your account balances
  • subscribe to order books on the exchange
  • view your open order requests
  • place new order requests 
  • cancel order requests
  • view your order history 
  • receive real-time market data.
     

2. REST:  By connecting to a REST channel, you can 

  • receive real-time price feeds,
  • access price charts,
  • view your trade history,
  • view your account balance,
  • view your open orders by pair,
  • cancel orders.  

    3. Financial Information eXchange (FIX): The FIX Protocol is a series of messaging specifications for the electronic communication of trade-related orders. This protocol has been developed by multiple banks, brokers, and exchanges. FIX is the leading protocol in trade communications, and it typically consists of placing and canceling trade orders, as well as receiving real-time market data and notifications. 

    Please note that the FIX API is only available on CEX.IO Prime.

    CEX.IO allows 60 requests per minute on its API channels. The REST API is better suited for dealing with your trade orders, while the WebSocket API is suited for both placing orders and getting market data. The WebSocket API provides three times more information per request than the REST API.

    The algorithms you need to connect to FIX, WS, and REST channels, along with the algorithms to send orders, stream market data and access your account balances, can be accessed on the CEX.IO website. Below are the links for the algorithm repository of each API channel:

    You can either copy and paste the relevant algorithms directly to your terminal if you have NodeJS, or adapt them accordingly to your programming language. 

    Additionally, CEX.IO has a Github repository, where you can access all API instructions developed in different programming languages to date. These include integrations to your terminal in Python, Node.js, Java, and C# languages.   

    Let’s explore some basic functions that you can automatically execute on different CEX.IO API channels.

     

    How to place an order with the REST API

    Here is a sample code that you can use to place automated bitcoin buy orders on the CEX.IO REST API from your terminal. To place different order types, just adjust the base and quote currency symbols (the first line in the code below), along with the type, amount, and price lines, according to your specific needs.

     For example, if you want to generate automated sell orders for Ethereum at predefined quantities and price levels in the future, just type “sell” on the type line and input your predetermined amounts and prices into the lines below. 

    POST https://cex.io/api/place_order/{ETH}/{USD}

    {

      “key”: “HLixH1aYdOIWOoRyoHkFpHlawrM”,

      “signature”: “0BDEDB9339DCE83D46F09A1527663762B52C8B12BCD1910E685BEAFEEABECFF9”,

      “nonce”: “1513175715”,

      “type”: “buy”,

      “amount”: 12,

      “price”: 3026.42

    }

    How to place an order with the Websocket API

    You can also place orders with the Websocket API like the sample code below. To change your order parameters, you need to adjust the base and quote currency symbols under the pair line (BTC and USD symbols in the below sample), along with the amount, price, and type lines, according to your specific requests:

    {

      “e”: “place-order”,

      “data”: {

        “pair”: [

          “BTC”,

          “USD”

        ],

        “amount”: 0.02,

        “price”: “43002.7“,

        “type”: “buy”

      },

      “oid”: “1435927928274_7_place-order”

    }

    How to check your account balance with the WebSocket API

    The sample code below illustrates how you can receive automated account balance messages with the WebSocket API. 

    {

        “e”: “get-balance”,

        “data”: {},

        “oid”: “1435927928274_2_get-balance”

    }

     

    In response, the WebSocket API will return with a message that contains your balances for the different assets in your CEX.IO account:

    {

        “e”: “get-balance”,

        “data”: {

               “balance”: {

                ‘LTC’: ‘10.00000000’, 

                ‘USD’: ‘1024.00’,

                ‘EUR’: ‘217.53’, 

                ‘BTC’: ‘9.00000000’

            },

                     },

           “time”: 1435927928597

        “oid”: “1435927928274_2_get-balance”,

        “ok”: “ok”

    }

    How to access your order books with the WebSocket API 

    Using the WebSocket API, you can subscribe to the order books of different cryptocurrency trading pairs. Here is how you can do it for the BTC/USD trading pair:

     {

      “e”: “order-book-subscribe”,

      “data”: {

      “pair”: [

            “BTC”,

            “USD”

            ],

            “subscribe”: false,

            “depth”: -1

      },

      “oid”: “1435927928274_3_order-book-subscribe”

      }

    You can check your orders for other pairs by adjusting the base and quote currencies in the pair section in the above code.

     

    Constructing API Crypto Trading Strategies on CEX.IO

    Third-party apps

    The majority of CEX.IO API traders use prebuilt, third-party applications that connect to the exchange. These applications import data from the CEX.IO exchange via APIs and allow traders to build their trading strategies. Traders can build strategies based on a plethora of indicators available on CEX.IO. Trading applications typically consist of a set of indicators, while some applications let you import additional indicators from other data sources.

    Crypto API trading with a third-party application requires little to no technical knowledge, because they are designed with prebuilt and intuitive interfaces where you can easily develop and implement your trading strategies. You will still need to have some understanding of trading indicators to develop a strategy. However, the majority of third-party applications have standard inputs for each of the indicators.

    CEX.IO has integrated with a number of third-party applications, making it all the more simple for traders to implement automated trading strategies. The following list includes the platforms and bots supported by CEX.IO:

    Developer apps

    Crypto API traders with better technical knowledge can develop trading applications from scratch. Developer-based trading applications are built using coding languages, such as Python, and plug into exchanges via APIs. Traders who develop their applications have the liberty of applying custom functions and adding any number of indicators to their strategies. This option has fewer limits, in terms of the capabilities and complexities of API crypto trading strategies. But, it is more difficult to use, compared to using a third-party application.

     

    API Trading Strategies

    Momentum

    Momentum trading is a trading play that uses volatility to capitalize on near-term trends. The scope of this strategy is to purchase assets (i.e. cryptocurrencies, stocks, etc.) as their values are rising, then sell them as they begin to decline. Another way is to purchase assets as they appear to have momentum, and sell when the momentum grows jaded. Examples of momentum indicators include, moving average convergence divergence (MACD), relative strength index (RSI), and combinations of near-term and longer term moving averages, among many others.

    Momentum trading is best practiced using multiple indicators and data from the exchange the user is using to trade. As such, it is a common strategy for API traders. Leveraging APIs, to trade using momentum, allows traders to build strategies around multiple indicators and manipulate exchange data to build other indicators, such as moving averages. Additionally, API trading, using a momentum strategy, allows traders to select specific trigger points within each indicator on which trades are made. The level of precision needed is hard to achieve as humans and it’s even more difficult to discover opportunities in the vast sea of cryptocurrencies.

    Arbitrage

    Arbitrage trading involves the exploitation of price disparities of the same asset across two or more markets. Arbitrage traders buy an asset in one market to sell the same asset in another market for a higher price. Arbitrage strategies often exploit minute price differences and are practiced at high volumes to drive profit. The small disparities in price often last seconds, and the need for higher volumes to realize benefits makes arbitrage a popular API trading strategy. The use of APIs allows price differences across markets to be identified immediately, while large capital allocations can be confidently moved with the precision of a computer.

    Sentiment

    Sentiment analysis and trading are based on the emotions of market participants; namely, if they are bullish or bearish. Capturing the emotions of the market is technology-driven and requires the use of APIs in more than one way. APIs play a role in retrieving the sentiment data that is used to determine market emotions and develop strategies, in addition to connecting the strategy to an exchange.

    Social media platforms are popular sources of sentiment data. Posts on social media can be pulled and analyzed for specific language, from which sentiment and sentiment-based strategies can be derived. Services that offer bundles of sentiment and sentiment-related data have grown increasingly popular. These providers have banks of data traders that tap into via APIs to develop strategies. The Tie and Augmento are examples of such providers.

    Volume-weighted average price (VWAP)

    The volume-weighted average price determines the average/price of an asset over a set period weighted by volume. VWAP is widely used as a benchmark for institutions and those who are looking to deploy larger amounts of capital. It is also a tool used by day traders and those looking to execute short-term bets. Price tends to gravitate towards the VWAP over a set period, thus deviations away from VWAP (either above or below VWAP price), can be used as opportunities to earn profit.

    The VWAP is calculated by putting the total amount of dollars traded for every transaction (price multiplied by the number of tokens traded) over the total dollar amount of tokens traded. In other words, (∑ Volume * Price) / ∑ Total Volume. The VWAP calculation must be updated after a new order has been executed and must use the data of the exchange that the trader is using.  The VWAP-based strategy is contingent on the use of exchange APIs.

     

    Arm your trades with crypto trading APIs 

    Cryptocurrency’s volatility is quite unforgiving and the fact that crypto markets are open 24/7 makes it almost impossible to rely entirely on manual trading. Both the physical and the psychological burdens of trading cryptocurrencies manually will take a toll on your emotions in the longer run, and you will likely end up blowing up your account.

    Automating trades with APIs allows you to create optimal and resilient trading strategies. You can program predetermined conditions in your terminal which would instruct the APIs to execute trades only when they are triggered. This will save you significant time and hassle, and give you flexibility, both in your trades and in your daily life. 

    With meticulously programmed APIs, you will be able to remove human emotions and error, reduce the chance of missing out on various trade opportunities, and take advantage of arbitrage opportunities, while simultaneously sending orders across multiple exchanges and markets.

    With three available API channels on CEX.IO – FIX, WebSocket and REST, you can satisfy all your trading, real-time market data, historical data, and account balance information needs, in an automated environment, directly from your terminal.

     

    Disclaimer: Information provided by CEX.IO is not intended to be, nor should it be construed as financial, tax or legal advice. The risk of loss in trading or holding digital assets can be substantial. You should carefully consider whether interacting with, holding, or trading digital assets is suitable for you in light of the risk involved and your financial condition. You should take into consideration your level of experience and seek independent advice if necessary regarding your specific circumstances. CEX.IO is not engaged in the offer, sale, or trading of securities. Please refer to the Terms of Use for more details.

     

    Related

    Education

    Will Bitcoin Ever Switch to Staking?

    Staking crypto is one of the ways to earn passive rewards as you hold coins in your balance. But why can’t you stake all the cryptocurrencies, just some designated ones?

    Sep 21, 2022 | 18 min read
    Education

    Bitcoin by the Numbers for The First Half of 2022

    We have just completed an article that dives into the details regarding Bitcoin’s performance for the first half of 2022. Enjoy!

    Aug 22, 2022 | 10 min read
    Education

    How to Use ChatGPT Effectively

    In our latest blog post, we explore how AI and ChatGPT-4 emerging tools are being utilized, and strategies for interacting with them more effectively.

    Apr 03, 2023 | 13 min read