A Bitmex Python Tutorial
BitMEX is a cryptocurrency trading platform that offers comprehensive API and supporting tools in addition to leverage trading, with varying leverage sizes depending on the product. Bitmex also provides a platform where it is possible to simulate trading called BitMEX Testnet without risking funds before doing any real investing.
In this tutorial, we will learn how to utilize Bitmex’s public API in order to fetch market data, fetch position data, set sell/buy orders, and finally update the leverage.
First of all, make sure that you already have signed in Bitmex and Bitmex Testnet. Then you can generate your API and Test API key for Bitmex.
Installation
$ pip install bitmex
Import the Library and Get Client Instance
In this tutorial we will proceed with Bitmex Testnet’s API to get the client instance.
import bitmex
import time, requests, jsonbitmex_api_key = <API_KEY> # Enter your own API-key here
bitmex_api_secret = <API_SECRET> # Enter your own API-secret hereclient = bitmex.bitmex(test = True, api_key=bitmex_api_key_test, api_secret=bitmex_api_secret_test)
Execute a Market Order
To execute an order we first have to fill some parameters. The first order would long 10 XBTUSD contracts at the current market price and the second would short 10 XBTUSD contracts at the current market price.
symbol = 'XBTUSD'
ordType = 'Market'
orderQty_Buy = 10 # Positive value to long
orderQty_Sell = -10 # Negative value to shortclient.Order.Order_new(symbol=symbol, ordType=ordType, orderQty=orderQty_Buy).result() # Longclient.Order.Order_new(symbol=symbol, ordType=ordType, orderQty=orderQty_Sell).result() # Short
Update Leverage
Since Bitmex offers leverage trading, we will be able to update the leverage of our positions using:
leverage = 5client.Position.Position_updateLeverage(symbol=symbol, leverage=leverage).result()
Close All Positions
All open positions of a certain symbol can be closed using:
client.Order.Order_closePosition(symbol=symbol).result()
Check Order History
To fetch our latest order history, we first set reverse=true
to get newest-first.
orders = client.Order.Order_getOrders(symbol=symbol, reverse=True).result()
To get the specific data from the orders we can clean the order using:
new_order = orders[0][0] # Get the last order
processed_order = {}
timestamp_minute = str(new_order["timestamp"]).split(':')[0] + ":" +
str(new_order["timestamp"]).split(':')[1] + ":00"
processed_order["symbol"] = new_order["symbol"]
processed_order["timestamp"] = timestamp_minute
processed_order["amount"] = str(new_order["orderQty"]).split("L")[0]
processed_order["price"] = new_order["price"]
processed_order["side"] = new_order["side"]
Check Open Positions
Check open positions of a certain symbol then select specific data using:
positions = client.Position.Position_get(filter=json.dumps({"symbol": symbol})).result()[0][0]processed_position = {}
timestamp_minute = str(positions["timestamp"]).split(':')[0] + ":" + \
str(positions["timestamp"]).split(':')[1] + ":00"
processed_position["symbol"] = positions["symbol"]
processed_position["timestamp"] = timestamp_minute
processed_position["isOpen"] = positions["isOpen"]
processed_position["currentQty"] = positions["currentQty"]
processed_position["leverage"] = positions["leverage"]
processed_position["liquidationPrice"] = positions["liquidationPrice"]
Get Past Minute Data
Fetch the past minute’s data of a certain symbol and select specific data using:
binSize='1m' # You can change the bin size as neededpast_minute_data = \
client.Trade.Trade_getBucketed(binSize=binSize, count=1, symbol=symbol, reverse=True).result()[0][0]
processed_min_data = {}
timestamp_minute = str(past_minute_data["timestamp"]).split(':')[0] + ":" + \
str(past_minute_data["timestamp"]).split(':')[1] + ":00"
processed_min_data["symbol"] = past_minute_data["symbol"]
processed_min_data["Date"] = timestamp_minute
processed_min_data["Open"] = past_minute_data["open"]
processed_min_data["Close"] = past_minute_data["close"]
processed_min_data["Volume"] = past_minute_data["volume"]
processed_min_data["High"] = past_minute_data["high"]
processed_min_data["Low"] = past_minute_data["low"]
You can also get the last couple of minutes if needed using:
number_of_minutes_needed = 20
past_minutes_data_list = []past_minutes_data = client.Trade.Trade_getBucketed(binSize='1m', count=number_of_minutes_needed, symbol=symbol, reverse=True).result()[0]past_minutes_data = reversed(past_minutes_data)
for past_minute_data in past_minutes_data:
processed_min_data = {}
timestamp_minute = str(past_minute_data["timestamp"]).split(':')[0] + ":" + str(past_minute_data["timestamp"]).split(':')[1] + ":00"
processed_min_data["symbol"] = past_minute_data["symbol"]
processed_min_data["Date"] = timestamp_minute
processed_min_data["Open"] = past_minute_data["open"]
processed_min_data["Close"] = past_minute_data["close"]
processed_min_data["Volume"] = past_minute_data["volume"]
processed_min_data["High"] = past_minute_data["high"]
processed_min_data["Low"] = past_minute_data["low"]
past_minutes_data_list.append(processed_min_data)
Also, Read
- The Best Crypto Trading Bots
- Deribit Review | Options, Fees, APIs and Testnet
- FTX Crypto Exchange Review
- The Best Bitcoin Hardware wallet
- Crypto Copy Trading Platforms
- The Best Crypto Tax Software
- Best Crypto Trading Platforms
- Best Crypto Lending Platforms
- Ledger vs Trezor
- Bitsgap review — A Crypto Trading Bot That Makes Easy Money
- Quadency Review- A Crypto Trading Bot Made For Professionals
- PrimeXBT Review | Leverage Trading, Fee and Covesting
- HaasOnline Review and Get a 10% discount
- The Idiots Guide to Margin Trading on Bitmex
- eToro Review | Trade Stocks, Crypto, ETFs, CFDs, and commodities
- Bitmex Advanced Margin Trading Guide
- Best Crypto APIs for Developers
- Crypto arbitrage guide: How to make money as a beginner
- Top Bitcoin Node Providers
- Best Crypto Charting Tool
- What are the best books to learn about Bitcoin?