hyperliquid-dex/hyperliquid-python-sdk

422 Client Error - Can't Figure Out What's Wrong

Closed this issue · 2 comments

I keep returning: Error fetching data for wif: 422 Client Error: Unprocessable Entity for url: https://api.hyperliquid.xyz/info

Here is my full code snippet:

import eth_account.account

from eth_account.signers.local import LocalAccount
import eth_account
import json
import time

from hyperliquid.info import Info
from hyperliquid.exchange import Exchange
from hyperliquid.utils import constants
import ccxt
import pandas as pd
import datetime
import schedule
import requests

symbol = 'wif'
timeframe = '4h'
size = 10


def ask_bid(symbol):
    # this gets ask and bid for any symbol passed in

    url = 'https://api.hyperliquid.xyz/info'
    headers = {'Content-type': 'application/json'}

    data = {
        'type': 'l2book',
        'coin': symbol
    }

    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
        response.raise_for_status()  # Raise an error for bad responses
        l2_data = response.json()
        l2_data = l2_data['levels']

        # get ask bid
        bid = float(l2_data[0][0]['px'])
        ask = float(l2_data[1][0]['px'])

        return ask, bid, l2_data

    except requests.exceptions.RequestException as e:
        print(f"Error fetching data for {symbol}: {e}")
        return None, None, None
    except (KeyError, ValueError) as e:
        print(f"Error parsing data for {symbol}: {e}")
        return None, None, None


def get_sz_px_decimals(coin):

    # this returns size decimals and price decimals
    url = 'https://api.hyperliquid.xyz/info'
    headers = {'Content-type': 'application/json'}
    data = {'type': 'meta'}

    try:
        response = requests.post(url, headers=headers, data=json.dumps(data))
        response.raise_for_status()  # Raise an error for bad responses
        data = response.json()
        symbols = data['universe']
        symbol_info = next((s for s in symbols if s['name'] == symbol), None)
        if symbol_info:
            sz_decimals = symbol_info['szDecimcals']
        else:
            print('symbol not found')
    except requests.exceptions.RequestException as e:
        print(f"Error fetching data for {coin}: {e}")
        return None, None
    except (KeyError, ValueError) as e:
        print(f"Error parsing data for {coin}: {e}")
        return None, None

    ask = ask_bid(symbol)[0]

    ask_str = str(ask)
    if '.' in ask_str:
        px_decimals = len(ask_str.split('.')[1])
    else:
        px_decimals = 0
    print(f'{symbol} this is the price {sz_decimals} decimals')

    return sz_decimals, px_decimals


def limit_order(coin, is_buy, sz, limit_px, reduce_only, account):
    exchange = Exchange(account, constants.MAINNET_API_URL)
    rounding = get_sz_px_decimals(coin)[0]
    sz = round(sz, rounding)
    print(f'coin: {coin}, type: {type(coin)}')
    print(f'is_buy: {is_buy}, type: {type(coin)}')
    print(f'sz: {sz}, type: {type(limit_px)}')
    print(f'reduce_only: {reduce_only}, type: {type(reduce_only)}')

    print(f'placing limit order for {coin} {sz} @ {limit_px}')
    order_result = exchange.order(coin, is_buy, sz, limit_px, {"limit": {"tif": 'Gtc'}}, reduce_only)
    if is_buy:
        print(f'limit BUY order placed thanks moon dev, resting: {order_result["response"]["data"]["statuses"][0]}')
    else:
        print(f'limit SELL order placed thanks moon dev, resting: {order_result["response"]["data"]["statuses"][0]}')

    return order_result


coin = symbol
is_buy = True  # false = sell
ask, bid, l2 = ask_bid(coin)
reduce_only = False
account = LocalAccount = eth_account.Account.from_key('omitted')

# buy order
if ask is not None:
    limit_order(coin, is_buy, bid, size, reduce_only, account)
else:
    print(f"Unable to place buy order for {coin}.")

time.sleep(5)

# sell order
is_buy = False
reduce_only = True
if bid is not None:
    limit_order(coin, is_buy, size, ask, reduce_only, account)
else:
    print(f"Unable to place sell order for {coin}.")
I worked through tons of bugs to get the code to connect but now I am stuck on next steps..

Note I have tried multiple symbols (requested a list directly from API) and have omitted my wallet key for obvious reasons in this example.

I recommend joining the discord and asking questions in the api-traders channel if you'd like assistance with debugging your code.