|
| 1 | +""" |
| 2 | +This example demonstrates how to round numbers when placing orders. |
| 3 | +Both Price (px) and Size (sz) have a maximum number of decimals that are accepted. |
| 4 | +Prices are precise to the lesser of 5 significant figures or 6 decimals. |
| 5 | +For example, 1234.5 is valid but 1234.56 is not. 0.001234 is valid, but 0.0012345 is not. |
| 6 | +Sizes are rounded to the szDecimals of that asset. |
| 7 | +For example, if szDecimals = 3 then 1.001 is a valid size but 1.0001 is not. |
| 8 | +You can find the szDecimals for an asset by making a meta request to the info endpoint |
| 9 | +""" |
| 10 | +from eth_account.signers.local import LocalAccount |
| 11 | +import eth_account |
| 12 | +import json |
| 13 | +import utils |
| 14 | + |
| 15 | +from hyperliquid.info import Info |
| 16 | +from hyperliquid.exchange import Exchange |
| 17 | +from hyperliquid.utils import constants |
| 18 | + |
| 19 | + |
| 20 | +def main(): |
| 21 | + config = utils.get_config() |
| 22 | + account: LocalAccount = eth_account.Account.from_key(config["secret_key"]) |
| 23 | + print("Running with account address:", account.address) |
| 24 | + info = Info(constants.TESTNET_API_URL, skip_ws=True) |
| 25 | + |
| 26 | + # Get the exchange's metadata and print it out |
| 27 | + meta = info.meta() |
| 28 | + print(json.dumps(meta, indent=2)) |
| 29 | + |
| 30 | + # create a szDecimals map |
| 31 | + sz_decimals = {} |
| 32 | + for info in meta["universe"]: |
| 33 | + sz_decimals[info["name"]] = info["szDecimals"] |
| 34 | + |
| 35 | + # For demonstration purposes we'll start with a price and size that have too many digits |
| 36 | + sz = 12.345678 |
| 37 | + px = 1.2345678 |
| 38 | + coin = "OP" |
| 39 | + |
| 40 | + # If you use these directly, the exchange will return an error, so we round them. |
| 41 | + # First we round px to 5 significant figures and 6 decimals |
| 42 | + px = round(float(f"{px:.5g}"), 6) |
| 43 | + |
| 44 | + # Next we round sz based on the sz_decimals map we created |
| 45 | + sz = round(sz, sz_decimals[coin]) |
| 46 | + |
| 47 | + print(f"placing order with px {px} and sz {sz}") |
| 48 | + exchange = Exchange(account, constants.TESTNET_API_URL) |
| 49 | + order_result = exchange.order(coin, True, sz, px, {"limit": {"tif": "Gtc"}}) |
| 50 | + print(order_result) |
| 51 | + |
| 52 | + # Cancel the order |
| 53 | + if order_result["status"] == "ok": |
| 54 | + status = order_result["response"]["data"]["statuses"][0] |
| 55 | + if "resting" in status: |
| 56 | + cancel_result = exchange.cancel(coin, status["resting"]["oid"]) |
| 57 | + print(cancel_result) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + main() |
0 commit comments