All Projects → HuobiRDCenter → Huobi_python

HuobiRDCenter / Huobi_python

Licence: apache-2.0
Python SDK for Huobi Spot API

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Huobi python

Huobi java
Java SDK for Huobi Spot API
Stars: ✭ 180 (-53.96%)
Mutual labels:  api, rest, cryptocurrency, sdk, websocket, exchange
Huobi golang
Go SDK for Huobi Spot API
Stars: ✭ 76 (-80.56%)
Mutual labels:  api, rest, cryptocurrency, sdk, websocket, exchange
Ccxt Rest
Open Source Unified REST API of 100+ Crypto Exchange Sites (18k+ docker pulls) - https://ccxt-rest.io/
Stars: ✭ 210 (-46.29%)
Mutual labels:  api, rest, cryptocurrency, exchange
Python Binance Chain
Binance Chain Exchange API python implementation for automated trading
Stars: ✭ 96 (-75.45%)
Mutual labels:  api, cryptocurrency, websocket
Foal
Elegant and all-inclusive Node.Js web framework based on TypeScript. 🚀.
Stars: ✭ 1,176 (+200.77%)
Mutual labels:  api, rest, sdk
Ccxt.net
CCXT.NET – CryptoCurrency eXchange Trading Library for .NET
Stars: ✭ 89 (-77.24%)
Mutual labels:  api, cryptocurrency, exchange
Currencyviewer
Short python framework that dynamically displays and converts the cryptocurrencies in your Kraken wallet into equivalents fiat money.
Stars: ✭ 13 (-96.68%)
Mutual labels:  api, cryptocurrency, exchange
Coinbase Pro Node
Coinbase Pro API written in TypeScript and covered by tests.
Stars: ✭ 116 (-70.33%)
Mutual labels:  api, cryptocurrency, exchange
Flickr Sdk
Almost certainly the best Flickr API client in the world for node and the browser
Stars: ✭ 104 (-73.4%)
Mutual labels:  api, rest, sdk
Bittrex.net
A C# .Net wrapper for the Bittrex web API including all features easily accessible and usable
Stars: ✭ 131 (-66.5%)
Mutual labels:  api, cryptocurrency, exchange
Poloniex Api Node
Poloniex API client for REST and WebSocket API
Stars: ✭ 138 (-64.71%)
Mutual labels:  api, rest, websocket
Jda
Java wrapper for the popular chat & VOIP service: Discord https://discord.com
Stars: ✭ 2,598 (+564.45%)
Mutual labels:  api, rest, websocket
Ccxws
WebSocket client for 38 cryptocurrency exchanges
Stars: ✭ 341 (-12.79%)
Mutual labels:  cryptocurrency, websocket, exchange
Openapi Generator
OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an OpenAPI Spec (v2, v3)
Stars: ✭ 10,634 (+2619.69%)
Mutual labels:  api, rest, sdk
Discord4j
Discord4J is a fast, powerful, unopinionated, reactive library to enable quick and easy development of Discord bots for Java, Kotlin, and other JVM languages using the official Discord Bot API.
Stars: ✭ 973 (+148.85%)
Mutual labels:  api, rest, websocket
Airdcpp Webclient
Communal peer-to-peer file sharing application for file servers/NAS devices
Stars: ✭ 106 (-72.89%)
Mutual labels:  api, rest, websocket
Exchangesharp
ExchangeSharp is a powerful, fast and easy to use .NET/C# API for interfacing with many crypto currency exchanges. REST and web sockets are supported.
Stars: ✭ 489 (+25.06%)
Mutual labels:  api, cryptocurrency, exchange
Python Poloniex
Poloniex API wrapper for Python 2.7 & 3
Stars: ✭ 557 (+42.46%)
Mutual labels:  api, cryptocurrency, exchange
Cryptocurrency Portfolio
Google Sheets automatic creation with Google Apps Script (GAS) for managing a cryptocurrency tracking spreadsheet with multi exchanges
Stars: ✭ 134 (-65.73%)
Mutual labels:  api, cryptocurrency, exchange
Coinapi Sdk
SDKs for CoinAPI
Stars: ✭ 238 (-39.13%)
Mutual labels:  api, sdk, exchange

Huobi Python SDK v2

This is Huobi Python SDK v2, you can import to your python project and use this SDK to query all market data, trading and manage your account. The SDK supports RESTful API invoking, and concurrently subscribing the market, account and order update from the Websocket connection.

If you already use SDK v1, it is strongly suggested migrate to v2 as we refactor the implementation to make it simpler and easy to maintain. We will stop the maintenance of v1 in the near future. Please refer to the instruction on how to migrate v1 to v2 in section Migrate from v1

Table of Contents

Quick Start

The SDK is compiled by Python 3.7 and above

You can download and open the source code directly in your python project, and then you can follow below steps:

  • Create the client instance.
  • Call the interfaces provided by client.
# Create generic client instance and get the timestamp
generic_client = GenericClient()
ts = generic_client.get_exchange_timestamp()
print(timestamp)

# 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)

Usage

After above section, this SDK should be already download to your local machine, this section introduce this SDK and how to use it correctly.

Folder structure

This is the folder and package structure of SDK source code and the description

  • huobi: The core of the SDK
    • client: The client that are responsible to access data, this is the external interface layer.
    • connection: Responsible to manage the remote server connection
    • constant: The constant configuration
    • exception: The wrapped exception
    • model: The server returned data model
    • service: The internal implementation for each client.
    • utils:The utility classes, including signature, json parser, logging etc.
  • performance: This is for internal performance testing
  • tests: This is for internal functional testing
  • example: The main package is defined here, it provides the examples how to use client instance to access API and read response.

Run examples

This SDK provides examples that under /example folder, if you want to run the examples to access private data, you need below additional steps:

  1. Create an API Key first from Huobi official website
  2. Create privateconfig.py into your huobi folder. The purpose of this file is to prevent submitting SecretKey into repository by accident, so this file is already added in the .gitignore file.
  3. Assign your API access key and secret key to as below:
p_api_key = "hrf5gdfghe-e74bebd8-2f4a33bc-e7963"
p_secret_key = "fecbaab2-35befe7e-2ea695e8-67e56"

If you don't need to access private data, you can ignore the API key.

Regarding the difference between public data and private data you can find details in Client section below.

Client

In this SDK, the client is the struct to access the Huobi API. In order to isolate the private data with public data, and isolated different kind of data, the client category is designated to match the API category.

All the client is listed in below table. Each client is very small and simple, it is only responsible to operate its related data, you can pick up multiple clients to create your own application based on your business.

Data Category Client Privacy API Protocol
Generic GenericClient Public Rest
Market MarketClient Public Rest, WebSocket
Account AccountClient Private Rest, WebSocket v2
Wallet WalletClient Private Rest
Trade TradeClient Private Rest, WebSocket v2
Margin MarginClient Private Rest
ETF ETFClient Private Rest

Customized Host

The client class support customized host so that you can define your own host, refer to example in later section.

Public and Private

There are two types of privacy that is correspondent with privacy of API:

Public client: It invokes public API to get public data (Generic data and Market data), therefore you can create a new instance without applying an API Key.

// Create a GenericClient instance
generic_client = GenericClient()

// Create a MarketClient instance with customized host
market_client = MarketClient(url="https://api-aws.huobi.pro")

Private client: It invokes private API to access private data, you need to follow the API document to apply an API Key first, and pass the API Key to the init function

// Create an AccountClient instance with APIKey
account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)

// Create a TradeClient instance with API Key and customized host
trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key, url="https://api-aws.huobi.pro")

The API key is used for authentication. If the authentication cannot pass, the invoking of private interface will fail.

Rest and WebSocket

There are two protocols of API, Rest and WebSocket

Rest: It invokes Rest API and get once-off response, it has two basic types of method: GET and POST

WebSocket: It establishes WebSocket connection with server and data will be pushed from server actively. There are two types of method for WebSocket client:

  • Request method: The method name starts with "Request-", it will receive the once-off data after sending the request.
  • Subscription: The method name starts with "Subscribe-", it will receive update after sending the subscription.

In this python SDK, some clients support both Rest and WebSocket protocols, the method name are prefixed and can be easily identified, take TradeClient as an example, the method prefix and their examples are:

  • get: get_order, get_matchresult
  • post: post_create_order, post_batch_cancel_open_order
  • req: req_order_list
  • sub: sub_order_update

Migrate from v1

Why v2

The major difference between v1 and v2 is that the client category.

In SDK v1, the client is categorized as two protocol, request client and subscription client. For example, for Rest API, you can operate everything in request client. It is simple to choose which client you use, however, when you have a client instance, you will have dozens of method, and it is not easy to choose the proper method.

The thing is different in SDK v2, the client class is categorized as seven data categories, so that the responsibility for each client is clear. For example, if you only need to access market data, you can use MarketClient without applying API Key, and all the market data can be retrieved from MarketClient. If you want to operate your order, then you know you should use TradeClient and all the order related methods are there. Since the category is exactly same as the API document, so it is easy to find the relationship between API and SDK. In SDK v2, each client is smaller and simpler, which means it is easier to maintain and less bugs.

How to migrate

You don't need to change your business logic, what you need is to find the v1 request client and subscription client, and replace with the proper v2 client. The additional cost is that you need to have additional initialization for each v2 client.

Request example

Reference data

Exchange timestamp

generic_client = GenericClient()
list_obj = generic_client.get_exchange_symbols()

Symbol and currencies

generic_client = GenericClient()
list_symbol = generic_client.get_exchange_symbols()
list_currency = generic_client.get_reference_currencies()

Market data

Candlestick

market_client = MarketClient()
list_obj = market_client.get_candlestick("btcusdt", CandlestickInterval.MIN5, 10)

Depth

market_client = MarketClient()
depth = market_client.get_pricedepth("btcusdt", DepthStep.STEP0, depth_size)

Latest trade

market_client = MarketClient()
list_obj = market_client.get_market_trade(symbol="btcusdt")

Historical

market_client = MarketClient()
list_obj = market_client.get_history_trade("btcusdt", 6)

Account

Authentication is required.

Get account balance

account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key)
account_balance_list = account_client.get_account_balance()

Wallet

Authentication is required.

Withdraw

wallet_client = WalletClient(api_key=g_api_key, secret_key=g_secret_key)
withdraw_id = wallet_client.post_create_withdraw(address="xxxxxx",
                                                     amount=40, currency="trx", fee=1,
                                                     chain=None, address_tag=None)

Cancel withdraw

wallet_client = WalletClient(api_key=g_api_key, secret_key=g_secret_key)
withdraw_id_ret = wallet_client.post_cancel_withdraw(withdraw_id=withdraw_id)

Withdraw and deposit history

wallet_client = WalletClient(api_key=g_api_key, secret_key=g_secret_key)
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)

Trading

Authentication is required.

Create order

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
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 order

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
canceled_order_id  = trade_client.cancel_order(symbol_test, order_id)

Cancel open orders

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
result  = trade_client.cancel_open_orders(account_id=g_account_id)

Get order info

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
orderObj = trade_client.get_order(order_id=order_id)

Historical orders

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key)
list_obj = trade_client.get_history_orders(symbol="btcusdt", start_time=None, end_time=None, size=20, direct=None)

Margin Loan

Authentication is required.

These are examples for cross margin

Apply loan

margin_client = MarginClient(api_key=g_api_key, secret_key=g_secret_key)
loan_id = margin_client.post_create_margin_order(symbol="eosusdt", currency="usdt", amount=loan_amount)

Repay loan

margin_client = MarginClient(api_key=g_api_key, secret_key=g_secret_key)
transfer_id = margin_client.post_repay_margin_order(loan_id=7440184, amount=100.004083)

Loan history

margin_client = MarginClient(api_key=g_api_key, secret_key=g_secret_key)
list_obj = margin_client.get_margin_loan_orders(symbol="eosusdt")

Subscription example

Subscribe trade update

def callback(trade_event: 'TradeDetailEvent'):
    print("---- trade_event:  ----")
    trade_event.print_object()
    print()

market_client = MarketClient()
market_client.sub_trade_detail("btcusdt,eosusdt", callback)

Subscribe candlestick update

def callback(candlestick_event: 'CandlestickEvent'):
    candlestick_event.print_object()
    print("\n")

def error(e: 'HuobiApiException'):
    print(e.error_code + e.error_message)

market_client = MarketClient()
market_client.sub_candlestick("btcusdt,ethusdt", CandlestickInterval.MIN1, callback, error)

Subscribe order update

Authentication is required.

def callback(upd_event: 'OrderUpdateEvent'):
    print("---- order update : ----")
    upd_event.print_object()
    print()

trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key, init_log=True)
trade_client.sub_order_update("eosusdt", callback)

Subscribe account change

Authentication is required.

def callback(account_change_event: 'AccountChangeEvent'):
    account_change_event.print_object()
    print()

account_client = AccountClient(api_key=g_api_key,
                              secret_key=g_secret_key,
                              init_log=True)
account_client.sub_account_update(AccountBalanceMode.TOTAL, callback)
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].