Market making bot for BitMEX API
Project description
BitMEX Market Maker
This is a sample market making bot for use with BitMEX.
It is free to use and modify for your own strategies. It provides the following:
- A
BitMEX
object wrapping the REST and WebSocket APIs.- All data is realtime and efficiently fetched via the WebSocket. This is the fastest way to get market data.
- Orders may be created, queried, and cancelled via
BitMEX.buy()
,BitMEX.sell()
,BitMEX.open_orders()
and the like. - Withdrawals may be requested (but they still must be confirmed via email and 2FA).
- Connection errors and WebSocket reconnection is handled for you.
- Permanent API Key support is included.
- A scaffolding for building your own trading strategies.
- Out of the box, a simple market making strategy is implemented that blankets the bid and ask.
- More complicated strategies are up to the user. Try incorporating index data, query other markets to catch moves early, or develop your own completely custom strategy.
Develop on Testnet first! Testnet trading is completely free and is identical to the live market.
BitMEX is not responsible for any losses incurred when using this code. This code is intended for sample purposes ONLY - do not use this code for real trades unless you fully understand what it does and what its caveats are.
This is not a sophisticated market making program. It is intended to show the basics of market making while abstracting some of the rote work of interacting with the BitMEX API. It does not make smart decisions and will likely lose money.
Getting Started
- Create a Testnet BitMEX Account and deposit some TBTC.
- Install:
pip install bitmex-market-maker
. It is strongly recommeded to use a virtualenv. - Create a marketmaker project: run
marketmaker setup
- This will create
settings.py
andmarket_maker/
in the working directory. - Modify
settings.py
to tune parameters.
- This will create
- Edit settings.py to add your BitMEX API Key and Secret and change bot parameters.
- Note that user/password authentication is not supported.
- Run with
DRY_RUN=True
to test cost and spread.
- Run it:
marketmaker [symbol]
- Satisfied with your bot's performance? Create a live API Key for your
BitMEX account, set the
BASE_URL
and start trading!
Operation Overview
This market maker works on the following principles:
- The market maker tracks the last
bidPrice
andaskPrice
of the quoted instrument to determine where to start quoting. - Based on parameters set by the user, the bot creates a descriptions of orders it would like to place.
- If
settings.MAINTAIN_SPREADS
is set, the bot will start inside the current spread and work outwards. - Otherwise, spread is determined by interval calculations.
- If
- If the user specifies position limits, these are checked. If the current position is beyond a limit, the bot stops quoting that side of the market.
- These order descriptors are compared with what the bot has currently placed in the market.
- If an existing order can be amended to the desired value, it is amended.
- Otherwise, a new order is created.
- Extra orders are canceled.
- The bot then prints details of contracts traded, tickers, and total delta.
Simplified Output
The following is some of what you can expect when running this bot:
2016-01-28 17:29:31,054 - INFO - market_maker - BitMEX Market Maker Version: 1.0
2016-01-28 17:29:31,074 - INFO - ws_thread - Connecting to wss://testnet.bitmex.com/realtime?subscribe=quote:XBT7D,trade:XBT7D,instrument,order:XBT7D,execution:XBT7D,margin,position
2016-01-28 17:29:31,074 - INFO - ws_thread - Authenticating with API Key.
2016-01-28 17:29:31,075 - INFO - ws_thread - Started thread
2016-01-28 17:29:32,079 - INFO - ws_thread - Connected to WS. Waiting for data images, this may take a moment...
2016-01-28 17:29:32,079 - INFO - ws_thread - Got all market data. Starting.
2016-01-28 17:29:32,079 - INFO - market_maker - Using symbol XBT7D.
2016-01-28 17:29:32,079 - INFO - market_maker - Order Manager initializing, connecting to BitMEX. Live run: executing real trades.
2016-01-28 17:29:32,079 - INFO - market_maker - Resetting current position. Cancelling all existing orders.
2016-01-28 17:29:33,460 - INFO - market_maker - XBT7D Ticker: Buy: 388.61, Sell: 389.89
2016-01-28 17:29:33,461 - INFO - market_maker - Start Positions: Buy: 388.62, Sell: 389.88, Mid: 389.25
2016-01-28 17:29:33,461 - INFO - market_maker - Current XBT Balance: 3.443498
2016-01-28 17:29:33,461 - INFO - market_maker - Current Contract Position: -1
2016-01-28 17:29:33,461 - INFO - market_maker - Avg Cost Price: 389.75
2016-01-28 17:29:33,461 - INFO - market_maker - Avg Entry Price: 389.75
2016-01-28 17:29:33,462 - INFO - market_maker - Contracts Traded This Run: 0
2016-01-28 17:29:33,462 - INFO - market_maker - Total Contract Delta: -17.7510 XBT
2016-01-28 17:29:33,462 - INFO - market_maker - Creating 4 orders:
2016-01-28 17:29:33,462 - INFO - market_maker - Sell 100 @ 389.88
2016-01-28 17:29:33,462 - INFO - market_maker - Sell 200 @ 390.27
2016-01-28 17:29:33,463 - INFO - market_maker - Buy 100 @ 388.62
2016-01-28 17:29:33,463 - INFO - market_maker - Buy 200 @ 388.23
-----
2016-01-28 17:29:37,366 - INFO - ws_thread - Execution: Sell 1 Contracts of XBT7D at 389.88
2016-01-28 17:29:38,943 - INFO - market_maker - XBT7D Ticker: Buy: 388.62, Sell: 389.88
2016-01-28 17:29:38,943 - INFO - market_maker - Start Positions: Buy: 388.62, Sell: 389.88, Mid: 389.25
2016-01-28 17:29:38,944 - INFO - market_maker - Current XBT Balance: 3.443496
2016-01-28 17:29:38,944 - INFO - market_maker - Current Contract Position: -2
2016-01-28 17:29:38,944 - INFO - market_maker - Avg Cost Price: 389.75
2016-01-28 17:29:38,944 - INFO - market_maker - Avg Entry Price: 389.75
2016-01-28 17:29:38,944 - INFO - market_maker - Contracts Traded This Run: -1
2016-01-28 17:29:38,944 - INFO - market_maker - Total Contract Delta: -17.7510 XBT
2016-01-28 17:29:38,945 - INFO - market_maker - Amending Sell: 99 @ 389.88 to 100 @ 389.88 (+0.00)
Advanced usage
You can implement custom trading strategies using the market maker. market_maker.OrderManager
controls placing, updating, and monitoring orders on BitMEX. To implement your own custom
strategy, subclass market_maker.OrderManager
and override OrderManager.place_orders()
:
from market_maker.market_maker import OrderManager
class CustomOrderManager(OrderManager):
def place_orders(self) -> None:
# implement your custom strategy here
Your strategy should provide a set of orders. An order is a dict containing price, quantity, and whether the order is buy or sell. For example:
buy_order = {
'price': 1234.5, # float
'orderQty': 100, # int
'side': 'Buy'
}
sell_order = {
'price': 9876.5, # float
'orderQty': 100, # int
'side': 'Sell'
}
Call self.converge_orders()
to submit your orders. converge_orders()
will create, amend,
and delete orders on BitMEX as necessary to match what you pass in:
def place_orders(self) -> None:
buy_orders = []
sell_orders = []
# populate buy and sell orders, e.g.
buy_orders.append({'price': 998.0, 'orderQty': 100, 'side': "Buy"})
buy_orders.append({'price': 999.0, 'orderQty': 100, 'side': "Buy"})
sell_orders.append({'price': 1000.0, 'orderQty': 100, 'side': "Sell"})
sell_orders.append({'price': 1001.0, 'orderQty': 100, 'side': "Sell"})
self.converge_orders(buy_orders, sell_orders)
To run your strategy, call run_loop()
:
order_manager = CustomOrderManager()
order_manager.run_loop()
Your custom strategy will run until you terminate the program with CTRL-C. There is an example
in custom_strategy.py
.
Notes on Rate Limiting
By default, the BitMEX API rate limit is 300 requests per 5 minute interval (avg 1/second).
This bot uses the WebSocket to greatly reduce the number of calls sent to the BitMEX API.
If you are quoting multiple contracts and your ratelimit is becoming an obstacle, please email support with details of your quoting. In the vast majority of cases, we are able to raise a user's ratelimit without issue.
Troubleshooting
Common errors we've seen:
TypeError: __init__() got an unexpected keyword argument 'json'
- This is caused by an outdated version of
requests
. Runpip install -U requests
to update.
- This is caused by an outdated version of
Compatibility
This module supports Python 3.5 and later.
See also
BitMEX has a Python REST client and websocket client.
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file bitmex-market-maker-1.6.1.tar.gz
.
File metadata
- Download URL: bitmex-market-maker-1.6.1.tar.gz
- Upload date:
- Size: 27.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 08cab7a30e14dd731ab8acb8291edcac48e3e36c98ee8889cfb7c870aff2b5fb |
|
MD5 | 3ddd367a1251b14f46ebc5b4c2f27d6e |
|
BLAKE2b-256 | bef5a9ed316d21590332847aaafce7d63cba4409f981c57d31d5afea41429751 |
File details
Details for the file bitmex_market_maker-1.6.1-py3-none-any.whl
.
File metadata
- Download URL: bitmex_market_maker-1.6.1-py3-none-any.whl
- Upload date:
- Size: 33.0 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/4.0.2 CPython/3.11.2
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 93c53cbb423cce4fbd83dceae4f6f7a5d7056b24b48c520ac3ef71dd7a9602de |
|
MD5 | 3364c5cab6a91ffcb54ed673fdcf2818 |
|
BLAKE2b-256 | 9adad8919f5baa27ec50d1e7345d1c8a9ee732a175a638ab7e429b5ec4683815 |