[Python] I'm trying to access the available balance in my Bybit futures account using the API,...

Discussão em 'Python' iniciado por Stack, Julho 6, 2025.

  1. Stack

    Stack Membro Participativo

    import requests
    import hashlib
    import hmac
    import time
    import json
    import urllib.parse

    API_KEY = "YOUR_BYBIT_API_KEY"
    SECRET_KEY = "YOUR_BYBIT_SECRET_KEY"

    BASE_URL = "https://api.bybit.com"
    ACCOUNT_INFO_ENDPOINT = "/v5/account/wallet-balance"
    CATEGORY = "linear"

    def get_bybit_futures_available_balance(api_key, secret_key, base_url, endpoint, category):
    try:
    req_time = int(time.time() \* 1000)

    headers_params = {
    "timestamp": req_time,
    "api_key": api_key,
    "recvWindow": 5000
    }

    query_params_for_url = {
    "category": category,
    }

    signature_query_string = urllib.parse.urlencode(sorted(query_params_for_url.items()))
    param_str = f"{headers_params['timestamp']}{headers_params['api_key']}{signature_query_string}"

    # DEBUG: String to sign
    print(f"DEBUG: String to sign: {param_str}")

    signature = hmac.new(secret_key.encode('utf-8'), param_str.encode('utf-8'), hashlib.sha256).hexdigest()

    # DEBUG: Generated signature
    print(f"DEBUG: Generated signature: {signature}")

    headers = {
    "X-BAPI-API-KEY": api_key,
    "X-BAPI-TIMESTAMP": str(headers_params["timestamp"]),
    "X-BAPI-RECVWINDOW": str(headers_params["recvWindow"]),
    "X-BAPI-SIGN": signature,
    "Content-Type": "application/json"
    }

    query_string_for_url = urllib.parse.urlencode(query_params_for_url)
    full_url = f"{base_url}{endpoint}?{query_string_for_url}"

    # DEBUG: Request URL
    print(f"DEBUG: Request URL: {full_url}")
    # DEBUG: Request headers
    print(f"DEBUG: Request headers: {headers}")

    response = requests.get(full_url, headers=headers)

    # DEBUG: HTTP Status Code
    print(f"DEBUG: HTTP Status Code: {response.status_code}")
    # DEBUG: Raw Response Text
    print(f"DEBUG: Raw Response Text: '{response.text}'")

    response.raise_for_status()

    balance_info = response.json()

    if balance_info.get("retCode") == 0 and "result" in balance_info:
    for account_type in balance_info["result"].get("list", []):
    if account_type.get("accountType") == CATEGORY:
    for coin_info in account_type.get("coins", []):
    print(f"{coin_info.get('coin', 'N/A')} Available Balance: {float(coin_info.get('availableToWithdraw', '0'))}")
    break
    else:
    print(f"Error: {balance_info.get('retMsg', 'Unknown error')}")
    return None

    except requests.exceptions.RequestException as e:
    print(f"Network or API request error: {e}")
    if hasattr(e, 'response') and e.response is not None:
    print(f"Response: {e.response.text}")
    except json.JSONDecodeError as e:
    print(f"JSON response parsing error: {e}. Response: '{response.text}'")
    except Exception as e:
    print(f"An unexpected error occurred: {e}")
    return None

    if __name__ == "__main__":
    if API_KEY == "YOUR_BYBIT_API_KEY" or SECRET_KEY == "YOUR_BYBIT_SECRET_KEY":
    print("Please update API_KEY or SECRET_KEY with your actual Bybit keys!")
    else:
    get_bybit_futures_available_balance(API_KEY, SECRET_KEY, BASE_URL, ACCOUNT_INFO_ENDPOINT, CATEGORY)


    There are error messages like below:

    DEBUG: String to sign: 17517792755041Sx7Z1YD4tpLE7fEjScategory=linear
    DEBUG: Generated signature: 3c1ec884338407d90d1b5d43ee2ac6336035125dc0f70edebe53c475da029dc4
    DEBUG: Request URL: https://api.bybit.com/v5/account/wallet-balance?category=linear
    DEBUG: Request headers: {'X-BAPI-API-KEY': '1Sx7Z1YD4tpLE7fEjS', 'X-BAPI-TIMESTAMP': '1751779275504', 'X-BAPI-RECVWINDOW': '5000', 'X-BAPI-SIGN': '3c1ec884338407d90d1b5d43ee2ac6336035125dc0f70edebe53c475da029dc4', 'Content-Type': 'application/json'}
    DEBUG: HTTP Status Code: 200
    DEBUG: Raw Response Text: '{"retCode":10001,"retMsg":"accountType is null.","result":{},"retExtInfo":{},"time":1751779275764}'
    Error: accountType is null.


    I think the error message means Bybit API received my request, but does not bring back what I want.

    Continue reading...

Compartilhe esta Página