If you've ever dabbled in the realm of cryptocurrency trading, you know that access to reliable and real-time data is crucial. The Hyperliquid API provides a robust way to interact with their decentralized exchange (DEX) for perpetual futures trading. Here, I want to walk you through setting up WebSocket feeds and managing orders using Python. This is based on my experience while building a trading bot for Hyperliquid.
Setting Up WebSocket Feeds
WebSocket feeds are essential for any trading bot, as they allow you to receive real-time market data. Hyperliquid’s API offers a WebSocket connection that streams live order book data, trades, and other updates. Let’s look at how you can establish a connection and start receiving data.
import websocket
import json
def on_message(ws, message):
data = json.loads(message)
print("Received data:", data)
def on_error(ws, error):
print("Error:", error)
def on_close(ws, close_status_code, close_msg):
print("WebSocket closed")
def on_open(ws):
print("WebSocket connection opened")
subscribe_message = json.dumps({
"type": "subscribe",
"channels": [{"name": "ticker", "product_ids": ["BTC-USD"]}]
})
ws.send(subscribe_message)
ws_url = "wss://api.hyperliquid.com/ws"
ws = websocket.WebSocketApp(ws_url,
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever()
The above snippet shows a basic setup to connect to the Hyperliquid WebSocket and subscribe to the ticker data for the BTC-USD pair. The on_message function handles incoming messages, which you can then process as needed for your trading strategies.
Managing Orders
Once you have real-time data, the next step is placing and managing orders. The API allows you to create, cancel, and modify orders. Here’s a simple example of placing an order using Python's requests library.
import requests
import hmac
import hashlib
import time
api_key = 'YOUR_API_KEY'
api_secret = 'YOUR_API_SECRET'
base_url = 'https://api.hyperliquid.com'
def create_order(product_id, side, price, size):
path = '/orders'
request_path = base_url + path
body = {
"product_id": product_id,
"side": side,
"price": price,
"size": size,
"order_type": "limit"
}
body_json = json.dumps(body)
timestamp = str(int(time.time()))
message = timestamp + 'POST' + path + body_json
signature = hmac.new(api_secret.encode('utf-8'), message.encode('utf-8'), hashlib.sha256).hexdigest()
headers = {
'Content-Type': 'application/json',
'CB-ACCESS-KEY': api_key,
'CB-ACCESS-SIGN': signature,
'CB-ACCESS-TIMESTAMP': timestamp
}
response = requests.post(request_path, headers=headers, data=body_json)
return response.json()
order_response = create_order("BTC-USD", "buy", "30000", "0.01")
print("Order Response:", order_response)
In this code, an HMAC signature is generated to authenticate the request. Make sure you replace 'YOUR_API_KEY' and 'YOUR_API_SECRET' with your actual API credentials. The create_order function is a straightforward way to place a limit order on the Hyperliquid exchange.
Putting It All Together
When I was piecing together my trading bot, the complexities of real-time data streaming and order management were significant. However, once the groundwork with WebSocket feeds and API requests was laid out, developing strategies such as momentum, mean-reversion, and breakout trading became much more manageable.
I actually packaged all this into a tool called the Hyperliquid Perpetual Futures Trading Bot. It’s designed to simplify perpetual futures trading on the Hyperliquid DEX with configurable leverage and built-in strategies. If you're interested, you can check it out here.
Working with Hyperliquid's API has been an enlightening experience, offering a glimpse into how decentralized platforms are shaping the future of trading. Whether you're building your bot from scratch or using an existing solution, the power of the API is at your fingertips.
Also available on Payhip with instant PayPal checkout.
If you need a server to run your bots 24/7, I use DigitalOcean — $200 free credit for new accounts.
Top comments (0)