BitMex API Introduction Guide

10 min read

Get 10-day Free Algo Trading Course

Last Updated on May 14, 2021

Table of contents:

  1. What is the BitMex API?
  2. What is BitMex?
  3. What Crypto Derivatives are available on BitMex?
  4. What are the trading fees on BitMex?
  5. Why should I use the BitMex API?
  6. Why shouldn’t I use the BitMex API?
  7. Is BitMex Available in my Country?
  8. What are the alternatives to using the BitMex API?
  9. What are the available libraries for the BitMex API?
  10. What is the BitMex Testnet?
  11. How to get started with the BitMex API?
  12. How do I execute a Market order with the BitMex API?
  13. How to change your leverage with the BitMex API?
  14. How to get a quote with the BitMex API?
  15. How to check open positions with the BitMex API?
  16. How to get past-minute data with the BitMex API?
  17. How to execute a trade on ETH when BTC hits a certain price with the BitMex API?
  18. How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the BitMex API?
  19. Are there any controversies concerning BitMex?
  20. Download Code Used

What is the BitMex API?

BitMex API is a method for us to trade cryptocurrencies on BitMex automatically via code.

What is BitMex?

The Bitcoin Mercantile Exchange (BitMex) is a trading platform that allows users to trade cryptocurrency derivative trading.

With BitMex, traders trade contracts that can be more volatile than those of traditional trading. Their platform is primarily built around trading cryptocurrencies through derivative trading or more specialized approaches like margin trading.

The volatility of BitMex is a double-edged sword which means that we can either generate mass profits with a small deposit, or lose much income in a quick manner.

As of lately, BitMex has updated its policy and requires the customer to follow the KYC regulation.

All currencies deposited on BitMex must be in Bitcoin, as the platform is specialized around it. When we deposit our Bitcoin, we can settle for contracts on various other currencies with it.

Have in mind that BitMEX only handles Bitcoin. All profit and loss are in Bitcoin, even if you’re buying and selling altcoin contracts. BitMEX does not handle fiat currency.

The notable coins are the following:

  • Bitcoin
  • Bitcoin Cash
  • Dash
  • Ripple
  • Ethereum
  • Ethereum Classic
  • Tezos
  • Chainlink
  • Monero
  • Tron
  • Litecoin
  • Zcash

Have in mind that Ethereum and Bitcoin trades have futures and spot trading options, whilst others have only the future markets.

What Crypto Derivatives are available on BitMex?

When it comes to contracts that BitMex provides there are a few:

  • Futures Contract – This can be viewed as an agreement to sell or buy a currency at a set price and time in the future.
  • Perpetual Contract – This one is similar to the previous one with the difference that it doesn’t expire.
  • Upside Profit Contract – According to BitMex, this allows us to pay a premium on the trade date for which we’re entitled to gain the difference between the underlying instrument settlement price and strike price on the maturity date, if positive. Otherwise, no payment is processed.
  • Downside Profit Contract – This is the opposite of the Upside Profit Contract and it allows us to take a part of a potential downside of a specified cryptocurrency.

What are the trading fees on BitMex?

When it comes to the fees BitMex applies to its users, they’re not too harsh. For example, if the Taker Fee is 0.0750%, while the Maker Fee is -0.0250%, the maker makes a small pay back on trades.

Takers are traders who buy at the ask price and sell at the bid price.

Makers are traders who buy at the bid price and sell at the ask price.

Withdrawals and deposits are free of charge which makes BitMex a competitive provider when compared with others.

The minimum amount that can be deposited into a BitMex trading account is 0.001 BTC, while there is no limit for the withdrawal amount. Fiat currencies aren’t available for withdrawal and deposits.

For a look into the full fee information, be sure to visit the following link: https://www.bitmex.com/app/fees

BitMex offers many order types like market orders, stop limit orders, take profit orders, stop limit orders, iceberg order, fill or kill, immediate or cancel, and more.

For the most part, BitMex doesn’t limit its user’s access depending on his geographical location, rather it is limited by the local laws of the residential country of the said user.

Following this, it is worthy to note that BitMex isn’t allowed in several countries and one of them is the US that assumed some illegal activities coming from BitMex.

If you want to learn how the BitMex indices are calculated, visit the following link: https://www.bitmex.com/app/indices

In my opinion, BitMex is most suitable for more experienced traders that have an understanding of the leverage function and the risks that go with it.

Why should I use the BitMex API?

  • Offers a wide range of cryptocurrencies for trading
  • Offers cryptocurrency derivatives
  • Offers valuable information on their website
  • Offers the leverage option (up to 100x)
  • The BitMex platform is customizable
  • No deposit and withdrawal fees
  • BitMex is transparent
  • High Liquidity
  • High Leverage
  • Good security
  • Has low fees

Why shouldn’t I use the BitMex API?

  • Only accepts Bitcoin for withdrawals and deposits
  • Not regulated in all countries (i.e. UK and US)
  • Doesn’t offer fiat withdrawals or deposits
  • Withdrawals are fixed to a set time of day
  • Doesn’t have a mobile application
  • Isn’t suitable for beginners

Is BitMex Available in my Country?

As of 5th January 2021, BitMex is not available in the following areas:

  • United States of America
  • Province of Ontario in Canada
  • Province of Québec in Canada
  • Hong Kong Special Administrative Region of the People’s Republic of China,
  • Republic of Seychelles
  • Bermuda
  • Cuba
  • Crimea
  • Sevastopol
  • Iran
  • Syria
  • North Korea
  • Sudan
  • Any state, country or other jurisdiction that is embargoed by the United States of America.

Source

What are the alternatives to using the BitMex API?

BitMex can be replaced with other application that can be more suitable for you needs. Here is the list:

  • Deribit
  • Coinbase
  • ByBit
  • Phemex
  • Binance
  • Bittrex
  • Kraken
  • Bittrex
  • Bitfinex
  • Poloniex
  • UPHOLD and more.

What are the available libraries for the BitMex API?

BitMex API uses a simple REST API that comes available in many languages like:

  • Python
  • C#
  • C++
  • Ruby
  • Scala
  • Java
  • PHP
  • JavaScript
  • Swift
  • NodeJS and more.

The full list can be obtained here: https://libraries.io/github/BitMEX/api-connectors

How to get started with the BitMex API?

In order to get started with the BitMex API, we’ll need to go to their website and register for an account. (https://www.bitmex.com/)

In the top right corner you’ll see a green “Register” button. Click it.

After that, we’ll input the required information (Email, Residence and Password) in the newly opened screen.

Now, the BitMex platform will send a confirmation email that we’ll need to check in order to proceed to the platform. After the confirmation, we’ll be led to a new screen.

Welcome to BitMex!

Let’s go ahead and setup an API Key. In the top toolbar click the “API” button. After that, click the API Key Management option under the API Keys section that is located on the left side of the screen.

Now, you’ll be able to give a name to your API Key for an easier referencing later, create a CIDR block to restrict it to a single IP address, add permission like Order and Order Cancel, and allow withdrawals.

After you’re set, click the “Create API Key” button.

What is the BitMex Testnet?

The BitMex API Testnet is an environment where we can test our programs and trading strategies. On the Testnet, all trading is free and is identical to the live trading market.

The only “annoying” thing is that you’ll need to go to the BitMex API Testnet and register on it. No matter if you already registered for the “real” one.

The registration process is the same and the API Key registration is the same too.

In order to differentiate the two BitMex environments, a logo variation was made. The regular BitMex API platform uses a red and blue logo while the BitMex API Testnet platform uses a green and blue logo.

How do I execute a Market order with the BitMex API?

For this article, we will use the Python programming language. Let’s go ahead and install our BitMex client with the following code:

pip install BitMex
pip install bitmex_websocket

Now, let’s import the relevant libraries that we need:

import bitmex
import time
import json
import requests

The next step is to add our API Key and API Secret and authenticate them so we can access the BitMex client.

bitmex_api_key = ”Your API Key Here” 
bitmex_api_secret = ”Your API Secret Here”
client = bitmex.bitmex(api_key=bitmex_api_key_test, api_secret=bitmex_api_secret_test)

Take note that the BitMex API client automatically connects us to the Testnet version. In order to connect to the real trading one, we’d need to write it as the following:

client = bitmex.bitmex(test = False, api_key=bitmex_api_key_test, api_secret=bitmex_api_secret_test)

After this, we’ll proceed to execute our market order. For this example we’ll trade the XBTEUR asset using the long and short contracts for the current market price.

We’ll need to specify our symbol, order type, and values for the long and short positions.

symbol = 'XBTUSD'
ordType = 'Market'
orderQty_Sell = -10 
orderQty_Buy = 10 

Now, let’s make the order calls for both long and short orders.

client.Order.Order_new(symbol=symbol, ordType=ordType, orderQty=orderQty_Sell).result() 

client.Order.Order_new(symbol=symbol, ordType=ordType, orderQty=orderQty_Buy).result() 

There is also another way to execute an order. For example if we want to buy 1000 XBTUSD contracts at $400, we’ll write the following:

client.Order.Order_new(symbol='XBTUSD', orderQty=1000, price=400).result()

In order to cancel all of our orders we can write the following:

client.Order.Order_cancelAll().result()

How to change your leverage with the BitMex API?

Leverages can be seen as borrowed funds that increase the returns from a specific investment or project. This means that they allow us to increase our buying power.

In order to change the leverage used with the BitMex API write the following code:

Leverage = 10
symbol = ‘XBTEUR’

client.Position.Position_updateLeverage (symbol = symbol, leverage = Leverage).result ()

How to get a quote with the BitMex API?

In order to get a quote from the BitMex API we’ll need to import the required library and specify the quote we want to obtain:

import bitmex
client = bitmex.bitmex()
result = client.Quote.Quote_get(symbol="XBTUSD", reverse=True, count=1).result()

Now, let’s ask for the bid price, bid size and the ask price:

result[0][0]['bidSize']

result[0][0]['bidSize']

result[0][0]['askPrice']

If you want to obtain all the quotes for today, you can write the following code:

client.Quote.Quote_get(symbol="XBTUSD", endTime=datetime.datetime.utcnow()).result()

How to check open positions with the BitMex API?

In order to get the open position we’ll need to add the following libraries:

import bitmex
import json
import datetime

After that, let’s start the client and get the position for the XBTUSD asset:

client.Position.Position_get(filter=json.dumps({'symbol': 'XBTUSD'})).result()

How to get past minute data with the BitMex API?

In order to get the past minute data with the BitMex API we’ll import the relevant libraries and authenticate our API Key:

import bitmex
import requests
import json
import datetime
import pandas as pd
bitmex_api_key = 'EeE092m3lwJism5mAFc4plfX' 
bitmex_api_secret = 'kgRLOsB7QOfauIyyNj5VOvPQ8ueLCuWWxwXTAI4ABcqqEMqk' 
client = bitmex.bitmex(api_key=bitmex_api_key, api_secret=bitmex_api_secret)

After this, let’s specify that we only want the past minute data and launch a call with the client:

binSize='1m'
past_minute_data = \
    client.Trade.Trade_getBucketed(binSize=binSize, count=1, symbol='XBTUSD', reverse=True).result()[0][0]

If you want to obtain past data from more than 1 minute, I got you. Let’s obtain data from the past 10 minutes with the following code:

number_of_minutes_needed = 20
past_minutes_data_list = []
past_minutes_data = client.Trade.Trade_getBucketed(binSize='1m', count=number_of_minutes_needed, symbol='XBTUSD', reverse=True).result()[0]

How to execute a trade on ETH when BTC hits a certain price with the BitMex API?

In this example, we will place a buy order on the Ethereum asset when the Bitcoin asset crosses above the 15076 price mark.

Firstly, let’s import the relevant libraries:

import bitmex
import requests
import json
import datetime
import pandas as pd
from time import sleep

After this, we will authenticate the API Key:

bitmex_api_key = 'EeE092m3lwJism5mAFc4plfX' 
bitmex_api_secret = 'kgRLOsB7QOfauIyyNj5VOvPQ8ueLCuWWxwXTAI4ABcqqEMqk' 
client = bitmex.bitmex(api_key=bitmex_api_key, api_secret=bitmex_api_secret)

Now, let’s see our XBTUSD asset and how it is performing overall. Also let’s clean up the results a bit.

positions = client.Position.Position_get(filter=json.dumps({"symbol": 'XBTUSD'})).result()[0][0]
positions['markPrice']

As we can see, our market price has already gone above the specified limit but what would we do if it was closer, for example, 15078.76?

Firstly, we would want to specify the currency we want to trade (Etherium) and the quantity of our market order:

symbol = 'ETHUSD'
ordType = 'Market'
orderQty_Buy = 100

The next step would be to create a loop that would fire every set of seconds (30) to check if the market price has gone above the specified level. If the price has gone above our level, we’d want to buy our Ethereium.

while True:
    if processed_position['markPrice'] < 15000:
       positions = client.Position.Position_get(filter=json.dumps({"symbol": 'XBTUSD'})).result()[0][0]
       processed_position = {}
       processed_position["markPrice"] = positions["markPrice"]
    else:
        if processed_position['markPrice'] > 15000:
            try:
                order = client.Order.Order_new(symbol=symbol, ordType=ordType, orderQty=orderQty_Buy).result()
                print(order)
                print ('Order placed at {}'.format(pd.Timestamp.now()))
                break
                
            except Exception as e:
                print("Error placing order:", e)
            
    sleep(30)

How to execute an ETH trade when BTC moves 5% in the last 5 minutes with the BitMex API?

There are many ways to do this and this example will follow a simple, beginner-friendly, way to solve the problem.

The first thing we want to do is import the required libraries:

import bitmex
import requests
import json
import datetime
from time import sleep

The next thing is to validate our API key:

bitmex_api_key = 'EeE092m3lwJism5mAFc4plfX' 
bitmex_api_secret = 'kgRLOsB7QOfauIyyNj5VOvPQ8ueLCuWWxwXTAI4ABcqqEMqk' 
client = bitmex.bitmex(api_key=bitmex_api_key, api_secret=bitmex_api_secret)

Now we shall specify the currency we want to buy, here being Etherium, the order type, and the quantity of it.

symbol = 'ETHUSD'
ordType = 'Market'
orderQty_Buy = 1000

Now, we need to make a logic by which the trade will occur. We want to make a loop that will start by obtaining the 5 minute candle with the opening price.

After it was obtained, we want our loop to sleep 5 minutes so we can get the new 5 minute candle.

The next step will be to calculate the percentage difference between the two obtained candles. If the percentage doesn’t match our desired 5 percent, the loop will continue.

On the other hand, if it does match our desired 5 percent we will place the order and break out of the loop. Sounds good?

Before I show the code, another way to do this was to obtain new candles every minute or less, and the code would be similar. You’d just need to change your candle size (binSize) and the sleep time.

while True:
    binSize='5m'
    start = \
    client.Trade.Trade_getBucketed(binSize=binSize, count=1, symbol='XBTUSD', partial =True, reverse=True).result()[0][0]
    
    print(start['open'])
    
    sleep (300)
    
    end = \
    client.Trade.Trade_getBucketed(binSize=binSize, count=1, symbol='XBTUSD', partial =True, reverse=True).result()[0][0]
    

    print(end['open'])
    
    percent = int(((end['open'] - start['open']) * 100) / start['open']) 
        
    if percent > 5:
        try:
            order = client.Order.Order_new(symbol=symbol, ordType=ordType, orderQty=orderQty_Buy).result()
            print(order)
            print ('Order placed at {}'.format(pd.Timestamp.now()))
            break

        except Exception as e:
            print("Error placing order:", e)
    
    else:
        print ('Did not move 5%')
        sleep (0.1)
        continue 

Are there any controversies concerning BitMex?

Yes! In May 2020, BitMex got sued by the US for evading rules designed to stop money laundering.

Accusations were made on the BitMex’s parent company (HDR Global Trading) and the top executives (Arthur Hayes, Samuel Reed, Ben Delo).

They were accused on several things and some of them are racketeering, operating a money transmitting business that’s not licensed, money laundering and fraud.

BitMex has disclosed in 2019 that almost 15% of its trading volume, which is worth around 138 billion dollars, was attributable to U.S. traders.

This means that they processed $3 billion in money transfers on a daily basis without having a license!

Arthur Hayes when asked why BitMex was opened in Seychelles said the following:

“Seychelles is cheaper to bribe than [the United States]’ and when asked how much he had to pay Seychelles to register BitMEX there, he said ‘a coconut.”

“But how was money laundering possible with BitMex?” – one may ask.

Well the Dolgov’s lawsuit described an example of how it occurs:

“A money launderer (Defendants) would open two exchange accounts – a helper account on one or more exchanges used by BitMEX to calculate its index price (Coinbase Pro, Kraken and BitStamp) and a winner account on BitMEX,” the lawsuit explains.

“The money launderer (Defendants) would then enter into a large leveraged derivatives position on BitMEX and immediately execute market orders from the helper account with maximum slippage to move the index price in a favorable direction.”

This article won’t take a side on either of the perspectives as the main point of it was to inform you about BitMex and its API.

Download Code Used

Github Link

Igor Radovanovic