Example: Placing Market Orders
This example demonstrates how to open and close a position using market orders.
Full Code (examples/basic_market_order.py
)
import time
import example_utils
from hyperliquid.utils import constants
def main():
address, info, exchange = example_utils.setup(constants.TESTNET_API_URL, skip_ws=True)
coin = "ETH"
is_buy = False
sz = 0.05
print(f"We try to Market {'Buy' if is_buy else 'Sell'} {sz} {coin}.")
order_result = exchange.market_open(coin, is_buy, sz, None, 0.01)
if order_result["status"] == "ok":
for status in order_result["response"]["data"]["statuses"]:
try:
filled = status["filled"]
print(f'Order #{filled["oid"]} filled {filled["totalSz"]} @{filled["avgPx"]}')
except KeyError:
print(f'Error: {status["error"]}')
print("We wait for 2s before closing")
time.sleep(2)
print(f"We try to Market Close all {coin}.")
order_result = exchange.market_close(coin)
if order_result["status"] == "ok":
for status in order_result["response"]["data"]["statuses"]:
try:
filled = status["filled"]
print(f'Order #{filled["oid"]} filled {filled["totalSz"]} @{filled["avgPx"]}')
except KeyError:
print(f'Error: {status["error"]}')
if __name__ == "__main__":
main()
Step-by-Step Explanation
- Setup: As usual,
example_utils.setup()
initializes the clients. - Market Open:
exchange.market_open(coin, is_buy, sz, None, 0.01)
is a convenience function for opening a position.- It places an aggressive limit order with a Time-in-Force of
Ioc
(Immediate or Cancel) to ensure it fills immediately against the order book. - The last argument,
0.01
, represents a 1% slippage tolerance. The SDK calculates a limit price 1% away from the current mid-price to ensure the market order is filled.
- Handling the Response: The response may contain multiple
filled
statuses if the order was filled against several resting orders. The code iterates through them and prints the details of each fill. - Market Close:
- After a 2-second pause,
exchange.market_close(coin)
is called. - This function automatically detects the existing position for the given
coin
, determines the required side (buy to close a short, sell to close a long) and size, and executes a market order to close the entire position.
- After a 2-second pause,