huobi_python SDK

repository·master·Indexed 20 days ago

https://github.com/huobirdcenter/huobi_python

A Python SDK for the Huobi (HTX) Spot API providing access to market data, trading, and account management via REST and WebSocket protocols. It features specialized client classes such as MarketClient, TradeClient, and AccountClient to isolate data categories and privacy levels. The SDK supports both one-off requests and real-time subscriptions for market and account updates, requiring Python 3.7 or above.

Tokens
3.2K
Snippets
9
Records
13
Agent score
22%

What's inside huobi_python

  1. Understand the Client Hierarchy and Data Categories

    master

    The SDK uses specialized client classes to isolate different types of data and privacy levels. This design matches the Huobi API categories, making it easier to find relevant methods.

    Data CategoryClientPrivacyAPI Protocol
    GenericGenericClientPublicRest
    MarketMarketClientPublicRest, WebSocket
    AccountAccountClientPrivateRest, WebSocket v2
    WalletWalletClientPrivateRest
    TradeTradeClientPrivateRest, WebSocket v2
    MarginMarginClientPrivateRest
    Sub UserSubuserClientPrivateRest
    AlgoAlgoClientPrivateRest
    ETFETFClientPrivateRest
  2. Understand Rest and WebSocket Method Naming Conventions

    master

    The SDK supports both RESTful API calls and WebSocket connections. Method names are prefixed to indicate the protocol and behavior:

    • Rest (One-off responses):
      • get_...: Standard GET request.
      • post_...: Standard POST request.
    • WebSocket:
      • req_... (Request): Sends a request via WebSocket and expects a one-off response.
      • sub_... (Subscription): Subscribes to a stream to receive continuous updates (e.g., order updates).
  3. Subscribe to Market and Account Updates

    master

    The SDK supports real-time subscriptions via callbacks.

    • Market Data: MarketClient.sub_trade_detail and MarketClient.sub_candlestick (no auth required).
    • Order Updates: TradeClient.sub_order_update (auth required).
    • Account Updates: AccountClient.sub_account_update (auth required).
    # Example: Subscribe to candlestick updates
    def callback(candlestick_event: 'CandlestickEvent'):
        candlestick_event.print_object()
    
    def error(e: 'HuobiApiException'):
        print(e.error_code + e.error_message)
    
    market_client = MarketClient()
    market_client.sub_candlestick("btcusdt,ethusdt", CandlestickInterval.MIN1, callback, error)
    
    # Example: Subscribe to order updates (Auth Required)
    def callback(upd_event: 'OrderUpdateEvent'):
        upd_event.print_object()
    
    trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key, init_log=True)
    trade_client.sub_order_update("eosusdt", callback)
    
    # Example: Subscribe to account changes (Auth Required)
    def callback(account_change_event: 'AccountChangeEvent'):
        account_change_event.print_object()
    
    account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key, init_log=True)
    account_client.sub_account_update(AccountBalanceMode.TOTAL, callback)
  4. Configure API Keys for Private Data

    master

    To access private data (Account, Trade, Wallet, etc.), you must create an API Key on the Huobi official website.

    To avoid accidentally committing sensitive credentials to version control, create a file named privateconfig.py inside the huobi folder. This file is ignored by .gitignore.

    Define your credentials in privateconfig.py as follows:

    p_api_key = "your_api_key"
    p_secret_key = "your_secret_key"
  5. Migrate from SDK v1 or v2 to v3

    master

    SDK v3 refactors the implementation to be more modular and consistent with the latest HTX open platform API.

    Key Changes:

    • Categorization: v1 used protocol-based clients (Request vs Subscription). v2 and v3 use data-category-based clients (Market, Trade, etc.).
    • Interface Updates: v3 has updated over 80 interfaces to match new parameter requirements and added over 130 new interfaces.

    Migration Steps:

    1. Identify the v1/v2 request or subscription client used in your business logic.
    2. Replace it with the corresponding v3 client (e.g., replace a generic request client with MarketClient or TradeClient).
    3. Add the necessary initialization for the new v3 client (including API keys if moving from public to private data).
  6. Quick Start with Huobi Python SDK v3

    master

    To use the SDK, ensure you are using Python 3.7 or above. You can integrate the SDK by importing the client classes and calling their methods.

    Basic workflow:

    1. Create a client instance (e.g., GenericClient or MarketClient).
    2. Call the desired interface method.

    Note: For public data, no API keys are required. For private data, you must provide an API key and secret key during initialization.

    # Create generic client instance and get the timestamp
    generic_client = GenericClient()
    ts = generic_client.get_exchange_timestamp()
    print(ts)
    
    # Create the market client instance and get the latest btcusdt‘s candlestick
    market_client = MarketClient()
    list_obj = market_client.get_candlestick("btcusdt", CandlestickInterval.MIN5, 10)
    LogInfo.output_list(list_obj)
  7. Access Market Data with MarketClient

    master

    Use MarketClient to fetch public market data including candlesticks, order book depth, latest trades, and historical trades. No authentication is required for these methods.

    market_client = MarketClient()
    
    # Get candlestick data
    # Requires symbol, CandlestickInterval, and count
    list_obj = market_client.get_candlestick("btcusdt", CandlestickInterval.MIN5, 10)
    
    # Get pricedepth
    # Requires symbol, DepthStep, and depth_size
    depth = market_client.get_pricedepth("btcusdt", DepthStep.STEP0, depth_size)
    
    # Get latest market trade
    list_obj = market_client.get_market_trade(symbol="btcusdt")
    
    # Get historical trades
    list_obj = market_client.get_history_trade("btcusdt", 6)
  8. Manage Accounts with AccountClient

    master

    Use AccountClient to manage account information. Authentication is required using api_key and secret_key.

    # Get account balance
    account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
    account_balance_list = account_client.get_account_balance()
  9. Manage Wallets with WalletClient

    master

    Use WalletClient to perform withdrawal operations and view history. Authentication is required.

    wallet_client = WalletClient(api_key=g_api_key, secret_key=g_secret_key)
    
    # Withdraw funds
    withdraw_id = wallet_client.post_create_withdraw(address="xxxxxx", amount=40, currency="trx", fee=1, chain=None, address_tag=None)
    
    # Cancel a withdrawal
    withdraw_id_ret = wallet_client.post_cancel_withdraw(withdraw_id=withdraw_id)
    
    # Get deposit/withdraw history
    # Use DepositWithdraw.DEPOSIT or DepositWithdraw.WITHDRAW
    # Use QueryDirection.PREV or QueryDirection.NEXT
    list_deposit_history = wallet_client.get_deposit_withdraw(op_type=DepositWithdraw.DEPOSIT, currency=None, from_id=1, size=10, direct=QueryDirection.PREV)
    list_withdraw_history = wallet_client.get_deposit_withdraw(op_type=DepositWithdraw.WITHDRAW, currency=None, from_id=1, size=10, direct=QueryDirection.NEXT)
  10. Manage Margin Loans with MarginClient

    master

    Use MarginClient for cross margin operations. Authentication is required.

    margin_client = MarginClient(api_key=g_api_key, secret_key=g_secret_key)
    
    # Apply for a loan
    loan_id = margin_client.post_create_margin_order(symbol="eosusdt", currency="usdt", amount=loan_amount)
    
    # Repay a loan
    transfer_id = margin_client.post_repay_margin_order(loan_id=7440184, amount=100.004083)
    
    # Get loan history
    list_obj = margin_client.get_margin_loan_orders(symbol="eosusdt")
  11. Execute Trades with TradeClient

    master

    Use TradeClient to manage orders. Authentication is required.

    trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
    
    # Create an order
    # Requires symbol, account_id, OrderType, OrderSource, amount, and price
    order_id = trade_client.create_order(symbol=symbol_test, account_id=account_id, order_type=OrderType.BUY_LIMIT, source=OrderSource.API, amount=4.0, price=1.292)
    
    # Cancel a specific order
    canceled_order_id = trade_client.cancel_order(symbol_test, order_id)
    
    # Cancel all open orders for an account
    result = trade_client.cancel_open_orders(account_id=g_account_id)
    
    # Get specific order info
    orderObj = trade_client.get_order(order_id=order_id)
    
    # Get historical orders
    list_obj = trade_client.get_history_orders(symbol="btcusdt", start_time=None, end_time=None, size=20, direct=None)
  12. Access Reference Data with GenericClient

    master

    Use GenericClient to retrieve non-authenticated exchange information such as available symbols and supported currencies.

    # Get exchange symbols
    generic_client = GenericClient()
    list_obj = generic_client.get_exchange_symbols()
    
    # Get symbols and reference currencies
    list_symbol = generic_client.get_exchange_symbols()
    list_currency = generic_client.get_reference_currencies()