Python Tutorial: How to Use the BitMEX API

Bit Romney
Coinmonks
3 min readDec 29, 2018

--

TL;DR

Learn how to place orders, cancel orders, and get price quotes from the BITMEX API using Python code. Scroll down to the bottom of this article to find the link to the simplest documentation.

Placing orders and all other functions are documented there and it’s easier to understand than the regular API docs.

This is a screenshot from the swagger.json file

Important Note on Syntax

When you’re looking for a specific function in the swagger.json file, use Cmd + F to search for the function you need (i.e. order).

Once you’ve found the operationId use the following to convert from operationId to actionable API call in your code.

In general:

Becomes:

Let’s turn the operationId ‘Order.getOrders’ from above into workable call.

```Order.getOrders```

Becomes

Where Order is the parentOperation and getOrders is the childOperation.

Now, for example, let’s say you wish to place many orders at once. Search the swagger.json file for ‘bulk’ and you will find Order.newBulk. Then, in your code

Becomes:

It’s a weird syntax so just copy/pasta. Be sure not to forget the .result() at the end of each call.

Below, I’ll work through a few examples of how I use the API. I’ll also go through errors and workarounds at the end.

Grateful as ever for ‘Claps’ and any feedback.

BitMEX Module Installation

Assuming you’re using python3.

Step 1

Install bravado

Step 2

Python Client

Python Client Authentication

Create a new python file. Include the following at the top of your file to instantiate the client.

Once you fill in the blanks with your api keys, your client is authenticated and you are ready to make real live API calls!

API Calls — Placing, listing, or cancelling orders

Place Order (operationId = Order.new)

Anytime we want to make an API call we just look for the corresponding Operation in the swagger.json file to make our call. Search the swagger.json file for the operationId you want, in this case Order.new. Then change

to

Don’t forget to add some parameters to your order:

The code above would long 10000 ETHUSD perpetual swap contracts at $390. Don’t forget the .result().

Cancel Orders (order.cancelAll)

If you would like to cancel all your orders, the operation id is Order.cancelAll. Here is the correct python syntax:

Common Errors

Forbidden 403 Error When Fetching Price Quote

You may get a forbidden 403 exception when trying to use the Quote endpoint as prescribed in the bitmex ReadMe. Fetching a price quote the prescribed way may yield this error:

But we need some way to get the Price. Here is a workaround to get ETHUSD Price:

Join Coinmonks Telegram Channel and Youtube Channel get daily Crypto News

Also, Read

--

--