All Projects → HuobiRDCenter → Huobi_java

HuobiRDCenter / Huobi_java

Licence: apache-2.0
Java SDK for Huobi Spot API

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Huobi java

Huobi python
Python SDK for Huobi Spot API
Stars: ✭ 391 (+117.22%)
Mutual labels:  api, rest, cryptocurrency, sdk, websocket, exchange
Huobi golang
Go SDK for Huobi Spot API
Stars: ✭ 76 (-57.78%)
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 (+16.67%)
Mutual labels:  api, rest, cryptocurrency, exchange
Crypto Trading Bot
Cryptocurrency trading bot in javascript for Bitfinex, Bitmex, Binance, FTX, Bybit ... (public edition)
Stars: ✭ 1,089 (+505%)
Mutual labels:  cryptocurrency, websocket, exchange
Python Kucoin
Kucoin REST and Websocket API python implementation
Stars: ✭ 165 (-8.33%)
Mutual labels:  rest, cryptocurrency, websocket
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 (+440.56%)
Mutual labels:  api, rest, websocket
Python Poloniex
Poloniex API wrapper for Python 2.7 & 3
Stars: ✭ 557 (+209.44%)
Mutual labels:  api, cryptocurrency, exchange
Ccxt.net
CCXT.NET – CryptoCurrency eXchange Trading Library for .NET
Stars: ✭ 89 (-50.56%)
Mutual labels:  api, cryptocurrency, exchange
Foal
Elegant and all-inclusive Node.Js web framework based on TypeScript. 🚀.
Stars: ✭ 1,176 (+553.33%)
Mutual labels:  api, rest, sdk
Python Binance Chain
Binance Chain Exchange API python implementation for automated trading
Stars: ✭ 96 (-46.67%)
Mutual labels:  api, cryptocurrency, websocket
Coinbase Pro Node
Coinbase Pro API written in TypeScript and covered by tests.
Stars: ✭ 116 (-35.56%)
Mutual labels:  api, cryptocurrency, exchange
Bitopro Api Node
Official nodejs SDK for the Bitopro(幣託) cryptocurrency exchange.
Stars: ✭ 29 (-83.89%)
Mutual labels:  cryptocurrency, sdk, exchange
Currencyviewer
Short python framework that dynamically displays and converts the cryptocurrencies in your Kraken wallet into equivalents fiat money.
Stars: ✭ 13 (-92.78%)
Mutual labels:  api, cryptocurrency, 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 (+5807.78%)
Mutual labels:  api, rest, sdk
Cryptofeed
Cryptocurrency Exchange Websocket Data Feed Handler
Stars: ✭ 643 (+257.22%)
Mutual labels:  cryptocurrency, websocket, exchange
Airdcpp Webclient
Communal peer-to-peer file sharing application for file servers/NAS devices
Stars: ✭ 106 (-41.11%)
Mutual labels:  api, rest, websocket
Bittrex.net
A C# .Net wrapper for the Bittrex web API including all features easily accessible and usable
Stars: ✭ 131 (-27.22%)
Mutual labels:  api, cryptocurrency, exchange
Poloniex Api Node
Poloniex API client for REST and WebSocket API
Stars: ✭ 138 (-23.33%)
Mutual labels:  api, rest, websocket
Go Binance
A Go SDK for Binance API
Stars: ✭ 441 (+145%)
Mutual labels:  api, sdk, exchange
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 (+171.67%)
Mutual labels:  api, cryptocurrency, exchange

Build Status

Huobi Java SDK v2

This is Huobi Java SDK v2, you can import to your project and use this SDK to query all market data, trading and manage your account. The SDK supports RESTful API invoking, and 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 Java8, you can import the source code in java IDE (idea or eclipse)

The example code are in folder /java/src/test/java/com/huobi/examples that you can run directly

If you want to create your own application, you can follow below steps:

  • Create the client instance.
  • Call the interfaces provided by client.
// Create GenericClient instance and get the timestamp
GenericClient genericService = GenericClient.create(HuobiOptions.builder().build());

Long serverTime = genericService.getTimestamp();
System.out.println("server time:" + serverTime);

// Create MarketClient instance and get btcusdt latest 1-min candlestick
MarketClient marketClient = MarketClient.create(new HuobiOptions());

List<Candlestick> list = marketClient.getCandlestick(CandlestickRequest.builder()
    .symbol("btcusdt")
    .interval(CandlestickIntervalEnum.MIN1)
    .size(10)
    .build());

list.forEach(candlestick -> {
  System.out.println(candlestick.toString());
});

Usage

Folder Structure

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

  • src/main/java/com/huobi: The core of the SDK
    • client: The client that are responsible to access data, this is the external interface layer
    • constant: The enum and constant definition
    • exception: The exception definition
    • model: The data model for response
    • service: The internal implementation for each client
    • utils: The utilities that include signature, websocket management etc
  • src/test/java/com/huobi: The test of the SDK
    • examples: The examples how to use client instance to access API and read response
    • service: The unit test for service package
    • test: The additional test such as performance test
    • utils: The unit test for utils package

Run Examples

This SDK provides examples that under src/test/java/com/huobi/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. Assign your API access key and secret key to "Constant.java" as below:
public static final String API_KEY = "hrf5gdfghe-e74bebd8-2f4a33bc-e7963"
public static final String 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 class 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
Sub user SubUserClient Private Rest
Trade TradeClient Private Rest, WebSocket v2
Algo AlgoClient Private Rest
Isolated margin IsolatedMarginClient Private Rest
Cross margin CrossMarginClient Private Rest
ETF ETFClient Private Rest

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
GenericClient genericService = GenericClient.create(new HuobiOptions());

// Create a MarketClient instance
MarketClient marketClient = MarketClient.create(new HuobiOptions());

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
AccountClient accountService = AccountClient.create(HuobiOptions.builder()
        .apiKey(Constants.API_KEY)
        .secretKey(Constants.SECRET_KEY)
        .build());

// Create a TradeClient instance with API Key
TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
        .apiKey(Constants.API_KEY)
        .secretKey(Constants.SECRET_KEY)
        .build());

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 "req-", it will receive the once-off data after sending the request.
  • Subscription: The method name starts with "sub-", it will receive update after sending the subscription.

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

GenericClient genericService = GenericClient.create(new HuobiOptions());
Long serverTime = genericService.getTimestamp();

Symbol and currencies

GenericClient genericService = GenericClient.create(new HuobiOptions());
List<Symbol> symbolList = genericService.getSymbols();
List<String> currencyList = genericService.getCurrencys();

Market data

Candlestick

MarketClient marketClient = MarketClient.create(new HuobiOptions());
List<Candlestick> list = marketClient.getCandlestick(CandlestickRequest.builder()
    .symbol(symbol)
    .interval(CandlestickIntervalEnum.MIN15)
    .size(10)
    .build());

Depth

MarketClient marketClient = MarketClient.create(new HuobiOptions());
MarketDepth marketDepth = marketClient.getMarketDepth(MarketDepthRequest.builder()
    .symbol(symbol)
    .depth(DepthSizeEnum.SIZE_5)
    .step(DepthStepEnum.STEP0)
    .build());

Latest trade

MarketClient marketClient = MarketClient.create(new HuobiOptions());
List<MarketTrade> marketTradeList = marketClient.getMarketTrade(MarketTradeRequest.builder().symbol(symbol).build());

Historical

MarketClient marketClient = MarketClient.create(new HuobiOptions());
List<MarketTrade> marketHistoryTradeList = marketClient.getMarketHistoryTrade(MarketHistoryTradeRequest.builder().symbol(symbol).build());

Account

Authentication is required.

Get account balance

AccountClient accountService = AccountClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
AccountBalance accountBalance = accountService.getAccountBalance(AccountBalanceRequest.builder()
    .accountId(accountId)
    .build());

Wallet

Authentication is required.

Withdraw

HuobiWalletService walletService = new HuobiWalletService(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
long withdrawId = walletService.createWithdraw(CreateWithdrawRequest.builder()
    .address(withdrawAddress)
    .addrTag(withdrawAddressTag)
    .currency("eos")
    .amount(new BigDecimal("1"))
    .fee(new BigDecimal("0.1"))
    .build());

Cancel withdraw

HuobiWalletService walletService = new HuobiWalletService(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
long res = walletService.cancelWithdraw(withdrawId);

Withdraw and deposit history

List<DepositWithdraw> depositWithdrawList = walletService.getDepositWithdraw(DepositWithdrawRequest.builder()
    .type(DepositWithdrawTypeEnum.WITHDRAW)
    .build());

Trading

Authentication is required.

Create order

TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
CreateOrderRequest buyLimitRequest = CreateOrderRequest.spotBuyLimit(spotAccountId, clientOrderId, symbol, bidPrice, new BigDecimal("2"));
Long buyLimitId = tradeService.createOrder(buyLimitRequest);

Cancel order

TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
int cancelResult = tradeService.cancelOrder(clientOrderId);

Cancel open orders

TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
BatchCancelOpenOrdersResult result = tradeService.batchCancelOpenOrders(BatchCancelOpenOrdersRequest.builder()
    .accountId(spotAccountId)
    .symbol(symbol)
    .build());

Get order info

TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
Order getOrder = tradeService.getOrder(51210074624L);

Historical orders

TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
List<Order> historyOrderList = tradeService.getOrdersHistory(OrderHistoryRequest.builder()
    .symbol(symbol)
    .startTime(1565107200000L)
    .direction(QueryDirectionEnum.PREV)
    .build());

Margin Loan

Authentication is required.

These are examples for cross margin

Apply loan

CrossMarginClient marginService = CrossMarginClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
Long applyId = marginService.applyLoan(CrossMarginApplyLoanRequest.builder()
    .currency("usdt")
    .amount(new BigDecimal("100"))
    .build());

Repay loan

CrossMarginClient marginService = CrossMarginClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
marginService.repayLoan(CrossMarginRepayLoanRequest.builder()
    .orderId(applyId)
    .amount(loanAmount)
    .build());

Loan history

CrossMarginClient marginService = CrossMarginClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
List<Balance> balanceList = crossMarginAccount1.getBalanceList()

Subscription example

Subscribe trade update

MarketClient marketClient = MarketClient.create(new HuobiOptions());
marketClient.subMarketTrade(SubMarketTradeRequest.builder().symbol(symbol).build(), (marketTradeEvent) -> {
    System.out.println("ch:" + marketTradeEvent.getCh());
    System.out.println("ts:" + marketTradeEvent.getTs());

    marketTradeEvent.getList().forEach(marketTrade -> {
      System.out.println(marketTrade.toString());
    });
});

###Subscribe candlestick update

MarketClient marketClient = MarketClient.create(new HuobiOptions());
marketClient.subCandlestick(SubCandlestickRequest.builder()
    .symbol(symbol)
    .interval(CandlestickIntervalEnum.MIN15)
    .build(), (candlestick) -> {

  System.out.println(candlestick.toString());
});

Subscribe order update

Authentication is required.

TradeClient tradeService = TradeClient.create(HuobiOptions.builder()
    .apiKey(Constants.API_KEY)
    .secretKey(Constants.SECRET_KEY)
    .build());
tradeService.subOrderUpdateV2(SubOrderUpdateV2Request.builder().symbols("*").build(), orderUpdateV2Event -> {
    System.out.println(orderUpdateV2Event.toString());
});

Subscribe account change

Authentication is required.

AccountBalance accountBalance = accountService.getAccountBalance(AccountBalanceRequest.builder()
    .accountId(accountId)
    .build());
accountService.subAccountsUpdate(SubAccountUpdateRequest.builder()
    .accountUpdateMode(AccountUpdateModeEnum.ACCOUNT_CHANGE).build(), event -> {
  System.out.println(event.toString());
});
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].