Code Monkey home page Code Monkey logo

jkorf / huobi.net Goto Github PK

View Code? Open in Web Editor NEW
72.0 7.0 50.0 4.83 MB

A C# .netstandard client library for the Huobi REST and Websocket Spot and Swap API focusing on clear usage and models

Home Page: https://jkorf.github.io/HTX.Net/

License: MIT License

C# 100.00%
huobi cryptocurrency tradeapi exchange huobipro huobinet csharp huobi-api houbi-net crypto cryptoexchange cryptoexchange-net huobi-future huobi-future-api huobi-swap huobi-swap-api htx htx-bot

huobi.net's Introduction

.HTX.Net HTX.Net

.NET License

HTX.Net, previously known as Huobi.Net, is a strongly typed client library for accessing the HTX REST and Websocket API.

Features

  • Response data is mapped to descriptive models
  • Input parameters and response values are mapped to discriptive enum values where possible
  • Automatic websocket (re)connection management
  • Client side rate limiting
  • Client side order book implementation
  • Extensive logging
  • Support for different environments
  • Easy integration with other exchange client based on the CryptoExchange.Net base library

Supported Frameworks

The library is targeting both .NET Standard 2.0 and .NET Standard 2.1 for optimal compatibility

.NET implementation Version Support
.NET Core 2.0 and higher
.NET Framework 4.6.1 and higher
Mono 5.4 and higher
Xamarin.iOS 10.14 and higher
Xamarin.Android 8.0 and higher
UWP 10.0.16299 and higher
Unity 2018.1 and higher

Install the library

NuGet

NuGet version Nuget downloads

dotnet add package JKorf.HTX.Net

GitHub packages

HTX.Net is available on GitHub packages. You'll need to add https://nuget.pkg.github.com/JKorf/index.json as a NuGet package source.

Download release

GitHub Release

The NuGet package files are added along side the source with the latest GitHub release which can found here.

How to use

REST Endpoints

// Get the ETH/USDT ticker via rest request
var restClient = new HTXRestClient();
var tickerResult = await restClient.SpotApi.ExchangeData.GetTickerAsync("ETHUSDT");
var lastPrice = tickerResult.Data.ClosePrice;

Websocket streams

// Subscribe to ETH/USDT ticker updates via the websocket API
var socketClient = new HTXSocketClient();
var tickerSubscriptionResult = socketClient.SpotApi.SubscribeToTickerUpdatesAsync("ETHUSDT", (update) =>
{
	var lastPrice = update.Data.ClosePrice;
});

For information on the clients, dependency injection, response processing and more see the HTX.Net documentation, CryptoExchange.Net documentation, or have a look at the examples here or here.

CryptoExchange.Net

HTX.Net is based on the CryptoExchange.Net base library. Other exchange API implementations based on the CryptoExchange.Net base library are available and follow the same logic.

CryptoExchange.Net also allows for easy access to different exchange API's.

Exchange Repository Nuget
Binance JKorf/Binance.Net Nuget version
BingX JKorf/BingX.Net Nuget version
Bitfinex JKorf/Bitfinex.Net Nuget version
Bitget JKorf/Bitget.Net Nuget version
BitMart JKorf/BitMart.Net Nuget version
Bybit JKorf/Bybit.Net Nuget version
CoinEx JKorf/CoinEx.Net Nuget version
CoinGecko JKorf/CoinGecko.Net Nuget version
Gate.io JKorf/GateIo.Net Nuget version
Kraken JKorf/Kraken.Net Nuget version
Kucoin JKorf/Kucoin.Net Nuget version
Mexc JKorf/Mexc.Net Nuget version
OKX JKorf/OKX.Net Nuget version

Discord

Nuget version
A Discord server is available here. Feel free to join for discussion and/or questions around the CryptoExchange.Net and implementation libraries.

Supported functionality

Spot Api

API Supported Location
Reference Data restClient.SpotApi.ExchangeData
Market Data restClient.SpotApi.ExchangeData
Account restClient.SpotApi.Account
Wallet restClient.SpotApi.Account
Sub user management restClient.SpotApi.SubAccount
Trading restClient.SpotApi.Trading
Conditional Order restClient.SpotApi.Trading
Margin Loan restClient.SpotApi.Account
Websocket Market Data socketClient.SpotApi
Websocket Account and Order socketClient.SpotApi

USDT-M Api

API Supported Location
Reference Data restClient.UsdtMarginSwapApi.ExchangeData
Swap Market Data Interface restClient.UsdtMarginSwapApi.ExchangeData
Swap Account Interface restClient.UsdtMarginSwapApi.Account
Swap Trade Interface restClient.UsdtMarginSwapApi.Trading
Swap Strategy Order Interface X
Swap Transferring Interface X restClient.SpotApi.Account
Websocket Market Interface socketClient.UsdtMarginSwapApi
Websocket Index and Basis Interface socketClient.UsdtMarginSwapApi
Orders And Account WebSocket X
WebSocket System updates X

Coin-M Futures Api

API Supported Location
* X

Coin-M Swap Api

API Supported Location
* X

Support the project

I develop and maintain this package on my own for free in my spare time, any support is greatly appreciated.

Donate

Make a one time donation in a crypto currency of your choice. If you prefer to donate a currency not listed here please contact me.

Btc: bc1q277a5n54s2l2mzlu778ef7lpkwhjhyvghuv8qf
Eth: 0xcb1b63aCF9fef2755eBf4a0506250074496Ad5b7
USDT (TRX) TKigKeJPXZYyMVDgMyXxMf17MWYia92Rjd

Sponsor

Alternatively, sponsor me on Github using Github Sponsors.

Release notes

  • Version 6.0.1 - 09 Aug 2024

    • Fixed websocket SpotApi queries (GetXX methods)
  • Version 6.0.0 - 08 Aug 2024

    • Renamed library from Huobi.Net to HTX.Net, following the renaming of the exchange
    • Renamed all models and references from Huobi... to HTX...
    • Renamed UsdtMarginSwapApi to UsdtFuturesApi
    • Renamed some endpoints to match standardized endpoint names
    • Split Margin and SubAccount endpoints into separate topics in the rest SpotApi
    • Split SubAccount endpoints into separate topics in the rest FuturesApi
    • Added UsdtFuturesSymbolOrderBook implementation
    • Added client side ratelimiting
    • Added various missing endpoints
    • Added Usdt Futures API account websocket streams
    • Updated from Newtonsoft.Json to System.Text.Json for json handling
    • Updated code xml comments
    • Updated API documentation references
    • Fixed a large number of bugs
  • Version 5.7.0 - 07 Aug 2024

  • Version 5.6.0 - 27 Jul 2024

  • Version 5.5.0 - 16 Jul 2024

  • Version 5.4.1 - 02 Jul 2024

  • Version 5.4.0 - 23 Jun 2024

  • Version 5.3.0 - 11 Jun 2024

  • Version 5.2.8 - 07 May 2024

  • Version 5.2.7 - 01 May 2024

  • Version 5.2.6 - 28 Apr 2024

  • Version 5.2.5 - 23 Apr 2024

  • Version 5.2.4 - 18 Apr 2024

  • Version 5.2.3 - 12 Apr 2024

    • Fix for futures broker id reference
  • Version 5.2.2 - 03 Apr 2024

    • Updated string comparision for improved performance
    • Fix for error parsing rest client
    • Removed pre-send symbol validation
  • Version 5.2.1 - 24 Mar 2024

  • Version 5.2.0 - 16 Mar 2024

  • Version 5.1.0 - 25 Feb 2024

    • Updated CryptoExchange.Net and implemented reworked websocket message handling. For release notes for the CryptoExchange.Net base library see: https://github.com/JKorf/CryptoExchange.Net?tab=readme-ov-file#release-notes
    • Fixed issue in DI registration causing http client to not be correctly injected
    • Removed redundant HuobiRestClient constructor overload
    • Updated some namespaces
  • Version 5.0.5 - 03 Dec 2023

    • Updated CryptoExchange.Net
  • Version 5.0.4 - 19 Nov 2023

    • Added support for sending broker id
  • Version 5.0.3 - 24 Oct 2023

    • Updated CryptoExchange.Net
  • Version 5.0.2 - 09 Oct 2023

    • Updated CryptoExchange.Net version
    • Added ISpotClient to DI injection
  • Version 5.0.1 - 25 Aug 2023

    • Updated CryptoExchange.Net
  • Version 5.0.0 - 25 Jun 2023

    • Updated CryptoExchange.Net to version 6.0.0
    • Renamed HuobiClient to HuobiRestClient
    • Renamed **Streams to **Api on the HuobiSocketClient
    • Updated endpoints to consistently use a base url without any path as basis to make switching environments/base urls clearer
    • Added IHuobiOrderBookFactory and implementation for creating order books
    • Updated dependency injection register method (AddHuobi)
  • Version 4.2.4 - 18 Mar 2023

    • Updated CryptoExchange.Net
  • Version 4.2.3 - 14 Feb 2023

    • Updated CryptoExchange.Net
  • Version 4.2.2 - 05 Feb 2023

    • Fixed leverageRate parameter for margin swap orders
  • Version 4.2.1 - 29 Dec 2022

    • Fixed GetCurrentFeeRatesAsync deserialization
  • Version 4.2.0 - 17 Nov 2022

    • Added Usdt Margin Swap API
    • Updated CryptoExchange.Net
    • Added user fee rate endpoint
  • Version 4.1.8 - 31 Jul 2022

    • Added missing account types
    • Fixed culture issue authenticating requests
  • Version 4.1.7 - 18 Jul 2022

    • Updated CryptoExchange.Net
  • Version 4.1.6 - 16 Jul 2022

    • Updated CryptoExchange.Net
  • Version 4.1.5 - 10 Jul 2022

    • Updated CryptoExchange.Net
  • Version 4.1.4 - 12 Jun 2022

    • Updated CryptoExchange.Net
  • Version 4.1.3 - 24 May 2022

    • Updated CryptoExchange.Net
  • Version 4.1.2 - 22 May 2022

    • Updated CryptoExchange.Net
  • Version 4.1.1 - 12 May 2022

    • Fixed CryptoExchange.Net reference
  • Version 4.1.0 - 12 May 2022

    • Added algo order endpoints
    • Added margin endpoints
    • Updated Url for partial order book stream
    • Removed symbol restriction on GetOpenOrdersAsync
  • Version 4.0.10 - 08 May 2022

    • Updated CryptoExchange.Net
  • Version 4.0.9 - 01 May 2022

    • Updated CryptoExchange.Net which fixed an timing related issue in the websocket reconnection logic
    • Added seconds representation to KlineInterval enum
  • Version 4.0.8 - 14 Apr 2022

    • Updated CryptoExchange.Net
  • Version 4.0.7 - 14 Mar 2022

    • Added GetUserIdAsync endpoint
    • Added GetSubAccountUsersAsync endpoint
    • Added GetSubUserAccountsAsync endpoint
  • Version 4.0.6 - 10 Mar 2022

    • Updated CryptoExchange.Net
    • Fixed CancellationToken not being passed to Common GetRecentTradesAsync
  • Version 4.0.5 - 08 Mar 2022

    • Updated CryptoExchange.Net
  • Version 4.0.4 - 01 Mar 2022

    • Updated CryptoExchange.Net improving the websocket reconnection robustness
  • Version 4.0.3 - 27 Feb 2022

    • Updated CryptoExchange.Net to fix timestamping issue when request is ratelimiter
  • Version 4.0.2 - 25 Feb 2022

    • Fixed missing Side property on GetUserTradeAsync response model
  • Version 4.0.1 - 24 Feb 2022

    • Updated CryptoExchange.Net
  • Version 4.0.0 - 18 Feb 2022

    • Added Github.io page for documentation: https://jkorf.github.io/Huobi.Net/

    • Added unit tests for parsing the returned JSON for each endpoint and subscription

    • Added AddHuobi extension method on IServiceCollection for easy dependency injection

    • Added URL reference to API endpoint documentation for each endpoint

    • Added default rate limiter

    • Refactored OrderType to be split in Type and Side to be consistent across exchange implementations

    • Refactored client structure to be consistent across exchange implementations

    • Renamed various properties to be consistent across exchange implementations

    • Cleaned up project structure

    • Fixed various models

    • Updated CryptoExchange.Net, see https://github.com/JKorf/CryptoExchange.Net#release-notes

    • See https://jkorf.github.io/Huobi.Net/MigrationGuide.html for additional notes for updating from V3 to V4

  • Version 3.2.4 - 03 Nov 2021

    • Fix for invalid check in SubscribeToOrderDetailsUpdatesAsync
  • Version 3.2.3 - 08 Oct 2021

    • Updated CryptoExchange.Net to fix some socket issues
  • Version 3.2.2 - 06 Oct 2021

    • Updated CryptoExchange.Net, fixing socket issue when calling from .Net Framework
    • Fixed issue in HuobiSymbolOrderBook syncing
  • Version 3.2.1 - 05 Oct 2021

    • Fixed incorrect sanity check in SubscribeToOrderUpdatesAsync
  • Version 3.2.0 - 29 Sep 2021

    • Added missing AccountTypes
    • Renamed Amount to Quantity in parameters and properties
    • Implemented Market-By-Price streams
    • Updated CryptoExchange.Net
  • Version 3.1.0 - 20 Sep 2021

    • Added missing SetApiCredentials method
    • Updated CryptoExchange.Net
  • Version 3.0.5 - 15 Sep 2021

    • Updated CryptoExchange.Net
  • Version 3.0.4 - 02 Sep 2021

    • Fix for disposing order book closing socket even if there are other connections
  • Version 3.0.3 - 26 Aug 2021

    • Updated CryptoExchange.Net
  • Version 3.0.2 - 24 Aug 2021

    • Updated CryptoExchange.Net, improving websocket and SymbolOrderBook performance
    • Fix for 15minute klines via IExchangeClient
  • Version 3.0.1 - 13 Aug 2021

    • Fix for OperationCancelledException being thrown when closing a socket from a .net framework project
  • Version 3.0.0 - 12 Aug 2021

  • Version 3.0.0-beta3 - 09 Aug 2021

    • Renamed GetOrderInfoAsync to GetOrderAsync
    • Renamed GetOrderInfoByClientOrderIdAsync to GetOrderByClientOrderIdAsync
    • Renamed GetSymbolTradesAsync to GetUserTradeHistoryAsync
    • Renamed PlaceWithdrawAsync to WithdrawAsync
    • Renamed GetTradesAsync to GetTradeHistoryAsync
  • Version 3.0.0-beta2 - 26 Jul 2021

    • Updated CryptoExchange.Net
  • Version 3.0.0-beta1 - 09 Jul 2021

    • Added Async postfix for async methods
    • Updated CryptoExchange.Net
  • Version 2.5.5 - 28 apr 2021

    • Updated CryptoExchange.Net
  • Version 2.5.4 - 19 apr 2021

    • Updated CryptoExchange.Net
  • Version 2.5.3 - 08 apr 2021

    • Added missing withdraw methods to client interface
  • Version 2.5.2 - 30 mrt 2021

    • Updated CryptoExchange.Net
    • Added missing methods in client interface
  • Version 2.5.1 - 01 mrt 2021

    • Added Nuget SymbolPackage
  • Version 2.5.0 - 01 mrt 2021

    • Added config for deterministic build
    • Updated CryptoExchange.Net
  • Version 2.4.0 - 22 jan 2021

    • Added GetWithdrawDeposit endpoint
    • Fixed ClientOrderId parsing
    • Updated for ICommonKline
  • Version 2.3.3 - 15 jan 2021

    • Updated PlaceOrder paramters
  • Version 2.3.2 - 14 jan 2021

    • Updated CryptoExchange.Net
  • Version 2.3.1 - 05 jan 2021

    • Fixed missing symbol property on socket ticker
  • Version 2.3.0 - 05 jan 2021

    • Added GetDepositAddress endpoint
    • Added Withdraw endpoint
    • Fix ClientOrderId deserialization on order
    • Added NextTime property for pagination on GetHistoryOrders
    • Updated HuobiOrderTrade model
    • Fixed ticker models
  • Version 2.2.0 - 21 dec 2020

    • Update CryptoExchange.Net
    • Updated to latest IExchangeClient
  • Version 2.1.1 - 11 dec 2020

    • Updated CryptoExchange.Net
    • Implemented IExchangeClient
  • Version 2.1.0 - 25 nov 2020

    • Updated account socket subscriptions to V2 API
  • Version 2.0.15 - 19 nov 2020

    • Added some V2 asset endpoints
    • Updated CryptoExchange.Net
  • Version 2.0.14 - 08 Oct 2020

    • Added symbol properties
    • Updated CryptoExchange.Net
  • Version 2.0.13 - 28 Aug 2020

    • Updated CryptoExchange.Net
  • Version 2.0.12 - 12 Aug 2020

    • Updated CryptoExchange.Net
  • Version 2.0.11 - 03 Aug 2020

    • Added best offer stream
  • Version 2.0.10 - 20 Jul 2020

    • Fixed transactionType mapping
  • Version 2.0.10 - 20 Jul 2020

    • Fixed TransactionType mapping
  • Version 2.0.9 - 07 Jul 2020

    • Fixed error parsing
    • Updated ticker model
  • Version 2.0.8 - 21 Jun 2020

    • Updated CryptoExchange
  • Version 2.0.7 - 16 Jun 2020

    • Updated CryptoExchange.Net
  • Version 2.0.6 - 07 Jun 2020

    • Updated CryptoExchange.Net to fix order book desync
  • Version 2.0.5 - 03 Mar 2020

    • Added clientOrderId to orders, added clientOrderId endpoints
  • Version 2.0.4 - 27 Jan 2020

    • Updated CryptoExchange.Net
  • Version 2.0.3 - 01 Nov 2019

    • Fixed websocket client authentication
  • Version 2.0.1 - 23 Oct 2019

    • Fixed validation length symbols again
  • Version 2.0.1 - 23 Oct 2019

    • Fixed validation length symbols
  • Version 2.0.0 - 23 Oct 2019

    • See CryptoExchange.Net 3.0 release notes
    • Added input validation
    • Added CancellationToken support to all requests
    • Now using IEnumerable<> for collections
    • Renamed Market -> Symbol
    • Renamed MarketDepth -> OrderBook
    • Renamed QueryXXX -> GetXXX
  • Version 1.1.9 - 11 Sep 2019

    • Updated CryptoExchange.Net
  • Version 1.1.8 - 07 Aug 2019

    • Updated CryptoExchange.Net
  • Version 1.1.7 - 05 Aug 2019

    • added code docs xml
  • Version 1.1.6 - 01 Aug 2019

    • Added HistoryOrders endpoint, made symbol parameter optional for order retrieving methods
  • Version 1.1.5 - 09 jul 2019

    • Updated HuobiSymbolOrderBook
  • Version 1.1.4 - 27 jun 2019

    • Added Loan and Interest to HuobiBalanceTypes enum, fixing deserialization issue
  • Version 1.1.3 - 24 jun 2019

    • Extended HuobiSymbol object
  • Version 1.1.2 - 17 may 2019

    • Fix for deserializing stop-orders created on the website
  • Version 1.1.1 - 17 may 2019

    • Added filter direction parameter to order/trade get methods
    • Added limit parameter to book depth
    • Added merge step parameter to order book implementation
  • Version 1.1.0 - 14 may 2019

    • Added 4 hour kline to enum
    • Added option to sign public requests to fix rate limiting issues
    • Added an order book implementation for easily keeping an updated order book
    • Added additional constructor to ApiCredentials to be able to read from file
  • Version 1.0.4 - 01 may 2019

    • Updated to latest CryptoExchange.Net
      • Adds response header to REST call result
      • Added rate limiter per API key
      • Unified socket client workings
    • Fixed authentication for russian API
  • Version 1.0.3 - 25 mar 2019

    • Added missing ConfigureAwait(false)
    • Made decimals nullable for new markets in market data
  • Version 1.0.2 - 18 mar 2019

    • Fixed amount parameter in PlaceOrder when precision = 0
  • Version 1.0.1 - 07 mar 2019

    • Updated CryptoExchange.Net
  • Version 1.0.0 - 27 feb 2019

    • Sub account support added
    • Fixed account type json mapping
    • Update CryptoExchange.Net
  • Version 0.0.5 - 15 feb 2019

    • Fixed sync issue while placing order concurrently
  • Version 0.0.4 - 12 feb 2019

    • Fixed order json mapping
  • Version 0.0.3 - 01 feb 2019

    • Updated CryptoExchange.Net
  • Version 0.0.2 - 17 dec 2018

    • Fix for reconnecting sometimes throwing an error
    • Fix for order update fields
  • Version 0.0.1 - 07 dec 2018

    • Initial release

huobi.net's People

Contributors

apollo4040 avatar babgev avatar burakoner avatar d-ugarov avatar ederksen avatar ericgarnier avatar espleth avatar georgef0 avatar golunikita avatar jkorf avatar jonnern avatar mboukhlouf avatar ridicoulous avatar samz-me avatar shigengyu avatar vmed avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

huobi.net's Issues

Missing mapping in AccountTypeConverter

There is a missing mapping for account type "super-margin" in the AccountTypeConverter class.
Calling GetAccountsAsync() will produce the issue, assuming you have a super-margin account

Incorrect fields in OrderUpdates

Hi! I found some fields in WebSocket did not return with correct values :

  1. Amount (should show order amount instead of 0)
  2. CanceledAt (should show order canceling time instead of min Time)
  3. Id (should show orderID instead of 0)
  4. Price (shown when order is placed, but not shown when order is canceled)

image

image

Wrong Deserialize ClientOrderID at HuobiOrder.cs

Hi There,
Thank you for the good work done.

I've found that the ClientOrderID isn't been deserialized because of the different field name.

Following the screenshot comparing the return vs the Class.
image

System.NullReferenceException in Huobi.Net.HuobiSymbolOrderBook.DoResyncAsync()

Hi JKorf,
I got a crash when a socket on Huobi try to reconnect.
The stack I can collect is :
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.
at Huobi.Net.HuobiSymbolOrderBook.DoResyncAsync()
at CryptoExchange.Net.OrderBook.SymbolOrderBook.ResyncAsync()
at CryptoExchange.Net.OrderBook.SymbolOrderBook.b__68_2(TimeSpan time)
at System.Threading.Tasks.Task.<>c.b__139_1(Object state)
at System.Threading.ThreadPoolWorkQueue.Dispatch()

Before this, I got the following warning:

2021/10/04 16:48:58:734 | Warning | Huobi | Huobi order book icxbtc connection lost
2021/10/04 16:48:58:734 | Information | Huobi | Huobi order book icxbtc status changed: Synced => Reconnecting
2021/10/04 16:49:03:802 | Information | Huobi | Huobi order book icxbtc status changed: Reconnecting => Syncing

Any idea what goes wrong?

Eric

GetAccounts() Error

private static void GetAccountBalances(Huobi.Net.HuobiClient client)
{
client.SetApiCredentials("", ""); // Change to your credentials
var accounts = client.GetAccounts();

Sir, when i used in this way, i cann't got the right feedback information, error msg show as below:
"Error deserializing data"

how can i fix this?

High and Close values but for 5 seconds candlesticks ?

Hello, and thank you very much for this C# component for accessing Huobi API.

I use the SubscribeToSymbolTickerUpdatesAsync function to get data from Huobi.

I receive data every 5 seconds.

I need to know if the Open and Close values are for 5-seconds candlesticks ?

Thanks.

Amount serialization issue in PlaceOrderAsync

For amount with value 1 serialized as 1.0 Huobi api returns order-orderamount-precision-error, order amount precision error, scale: 0

The issue is exist only for symbols with quantity step size 1 like elfbtc.

As a temporary fix, I replaced { "amount", amount } to { "amount", amount.ToString() }

Authentication failed: Server error: No response from server

When I use Websocket access to anonymous endpoints such as "SubscribeToKlineUpdatesAsync",it works well,but when I access to authenticated endpoints such as "SubscribeToOrderUpdatesAsync"、"SubscribeToAccountUpdatesAsync",the server response:
Authentication failed: Server error: No response from server 。
HuobiSocketClientOptions huobiSocketClientOptions = new HuobiSocketClientOptions()
{
ApiCredentials = new ApiCredentials(_apiKey, _apiSecret)
};
using (HuobiSocketClient huobiSocketClient = new HuobiSocketClient(huobiSocketClientOptions))
{
.......
}

I use the same key and secret access to HuobiClient(Rest),it works well.

Mutile-thread problem (SafeHandle cannot be null)

I got a "SafeHandle cannot be null" error while trying to place 3 orders at a time.

image

System.ArgumentNullException
HResult=0x80004003
Message=SafeHandle cannot be null.
Source=System.Private.CoreLib
StackTrace:
at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource)
at System.StubHelpers.StubHelpers.SafeHandleAddRef(SafeHandle pHandle, Boolean& success)
at Interop.BCrypt.BCryptHashData(SafeBCryptHashHandle hHash, Byte& pbInput, Int32 cbInput, Int32 dwFlags)
at Internal.Cryptography.HashProviderCng.AppendHashData(ReadOnlySpan1 source) at Internal.Cryptography.HashProvider.AppendHashData(Byte[] data, Int32 offset, Int32 count) at System.Security.Cryptography.HMACSHA256.HashCore(Byte[] rgb, Int32 ib, Int32 cb) at System.Security.Cryptography.HashAlgorithm.ComputeHash(Byte[] buffer) at Huobi.Net.HuobiAuthenticationProvider.AddAuthenticationToParameters(String uri, String method, Dictionary2 parameters, Boolean signed) in K:\Huobi.Net\HuobiAuthenticationProvider.cs:line 51
at Huobi.Net.HuobiClient.ConstructRequest(Uri uri, String method, Dictionary2 parameters, Boolean signed) in K:\Huobi.Net\HuobiClient.cs:line 585 at CryptoExchange.Net.RestClient.<ExecuteRequest>d__241.MoveNext()

any advice? thank you.

Huobi symbols

Hi!
Have you seen that symbols model was extended?
Here are the example:
{"base-currency":"powr","quote-currency":"eth","price-precision":8,"amount-precision":0,"symbol-partition":"innovation","symbol":"powreth","state":"online","value-precision":8,"min-order-amt":0.1,"max-order-amt":500000,"min-order-value":0.001}

As you can see here are couple of new fields:
"state":"online",
"value-precision":8,
"min-order-amt":0.1,
"max-order-amt":500000,
"min-order-value":0.001

I don't know what's the purpose of this fields, but maybe you can update HuobiSymbol class?

Futures/Swaps support

It does not seem to me that futures or swaps support is available, unless I missed it. Are there any plans for implementation? Or if available, any examples?

ClientOrderId Support

Is the Authentication in socketClient missing?

Hi! Seems like I have failed to use the "SubscribeToOrderUpdates" function in socketClient because I could not find a place to authenticate myself like what I did in REST request

 using (var socketClient = new HuobiSocketClient())
                {
                    //Able to listen
                    socketClient.SubscribeToMarketKlineUpdates("ethusdt", HuobiPeriod.FiveMinutes, data =>
                    {
                        Console.WriteLine("Received kline update. Last price: " + data.Close);

                    });

                    //Unable to listen
                    socketClient.SubscribeToOrderUpdates(data =>
                    {
                        Console.WriteLine("Received order update. Last price: " + data.ToString());
                    });
                    Console.ReadLine();
                }

Is the Authentication in socketClient missing, or is there any problem with my code?

Thanks,!

Huobi GetTickers missing fields

Hi,
The returning of GetTickers aren't bringing some fields.

It should return the following structure {"symbol":"creusdt","open":0.002164,"high":0.00233,"low":0.002141,"close":0.002273,"amount":1.907087512791328E8,"vol":421097.89436649525,"count":5083,"bid":0.002273,"bidSize":105032.78,"ask":0.002275,"askSize":880000.0}

and it's returning the following fields only {
  Amount | 67657173.06086831 |
  Close | 0.0000003189 |
  High | 0.0000003441 |
  Low | 0.0000002916 |
  Open | 0.0000003317 |
  Symbol | "tnbbtc" |
  TradeCount | 4341 |
  Volume | 21.692119019828027 |
}

Maybe you could update that class ?

SubscribeToMarketDepthUpdates failed

Unhandled Exception: System.AggregateException: One or more errors occurred. (One or more errors occurred. (Object reference not set to an instance of an object.)) ---> System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.
at CryptoExchange.Net.Sockets.BaseSocket.b__72_0()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location where exception was thrown ---
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot)
--- End of stack trace from previous location where exception was thrown ---
at CryptoExchange.Net.Sockets.BaseSocket.Close()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
at System.Threading.Tasks.Task.Wait()
at CryptoExchange.Net.Sockets.BaseSocket.b__75_5()
at System.Threading.Tasks.Task1.InnerInvoke() at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state) --- End of stack trace from previous location where exception was thrown --- at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot) --- End of stack trace from previous location where exception was thrown --- at CryptoExchange.Net.Sockets.BaseSocket.Connect() at CryptoExchange.Net.SocketClient.ConnectSocket(SocketSubscription socketSubscription) at Huobi.Net.HuobiSocketClient.CreateAndConnectSocket[T](Boolean authenticate, Boolean sub, Action1 onMessage) in K:\test\Huobi.Net\HuobiSocketClient.cs:line 630
at Huobi.Net.HuobiSocketClient.Subscribe[T](HuobiRequest request, Action1 onData) in K:\test\Huobi.Net\HuobiSocketClient.cs:line 447 at Huobi.Net.HuobiSocketClient.SubscribeToMarketDepthUpdatesAsync(String symbol, Int32 mergeStep, Action1 onData) in K:\test\Huobi.Net\HuobiSocketClient.cs:line 162
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at Huobi.Net.HuobiSocketClient.SubscribeToMarketDepthUpdates(String symbol, Int32 mergeStep, Action1 onData) in K:\test\Huobi.Net\HuobiSocketClient.cs:line 142
at ConsoleApp1.OrderR.InitWSClient()
at ConsoleApp1.OrderR.Run()
at ConsoleApp1.Program.Main(String[] args)

Doesn't work with Huobi Russia

The Huobi Russia has another API URL
https://www.huobi.com.ru/api

The library can't make valid signature for this URL.
Because you should remove "/api" part of path.

I made some changes in the HuobiAuthenticationProvider class and it works fine.

var absolutePath = uriObj.AbsolutePath; if (absolutePath.StartsWith("/api")) absolutePath = absolutePath.Substring(4); signData += absolutePath + "\n";

Rate Limit Problem

Hi, @JKorf

I've an multithread application using Huobi.Net package.

I load main thread (windows service main thread), then I set RateLimitOptions via static way as below:

this.HuobiNetClientOptions = new Huobi.Net.HuobiClientOptions() { RateLimiters = new List<CryptoExchange.Net.Interfaces.IRateLimiter> { new CryptoExchange.Net.RateLimiter.RateLimiterTotal(60, TimeSpan.FromSeconds(10)), }, RateLimitingBehaviour = CryptoExchange.Net.Objects.RateLimitingBehaviour.Wait, RequestTimeout = TimeSpan.FromSeconds(30), }; Huobi.Net.HuobiClient.SetDefaultOptions(this.HuobiNetClientOptions); this.HuobiNetClient = new Huobi.Net.HuobiClient();

And I start 6 threads too and these threads uses HuobiClient in main thread. So I use same object for all threads. I use only getting klines method in API. Huobi allows 100 request in 10 seconds, Even I set for 60 requests I got rate limit error.

By the way, I use your Binance.Net package in same method and I dont get rate limit error in Binance.

Could you please check it?

Unhandled Exception in WebSocket4Net

12:21:16.85[165566]DEBUG:[Huobi] API: 2019/05/29 12:21:10:653 | Info | Socket 572 error: System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.BeginReceive(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
at System.Net.Sockets.NetworkStream.BeginRead(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
--- End of inner exception stack trace ---
at System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)
at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.OnDataRead(IAsyncResult result)

12:21:16.85[166200]DEBUG:[Huobi] API: 2019/05/29 12:21:12:568 | Info | Socket 572 error: System.IO.IOException: Unable to write data to the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException: An established connection was aborted by the software in your host machine
at System.Net.Sockets.Socket.BeginSend(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, AsyncCallback callback, Object state)
at System.Net.Sockets.NetworkStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 size, AsyncCallback callback, Object state)
at System.Net.Security._SslStream.StartWriting(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.ProcessWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncProtocolRequest asyncRequest)
at System.Net.Security._SslStream.BeginWrite(Byte[] buffer, Int32 offset, Int32 count, AsyncCallback asyncCallback, Object asyncState)

12:21:19.84[157352]FATAL:UnhandledException:
System.NullReferenceException: Object reference not set to an instance of an object.
at WebSocket4Net.Protocol.DraftHybi10Processor.SendHandshake(WebSocket websocket)
at SuperSocket.ClientEngine.AuthenticatedStreamTcpSession.OnAuthenticatedStreamConnected(AuthenticatedStream stream)
at SuperSocket.ClientEngine.SslStreamTcpSession.OnAuthenticated(IAsyncResult result)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Security.SslState.FinishHandshake(Exception e, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.CheckCompletionBeforeNextReceive(ProtocolToken message, AsyncProtocolRequest asyncRequest)
at System.Net.Security.SslState.WriteCallback(IAsyncResult transportResult)
at System.Net.LazyAsyncResult.Complete(IntPtr userToken)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)

Enum updates

Huobi supports 4Hours Klines. can you add please?

HuobiEnums.cs
public enum HuobiPeriod { OneMinute, FiveMinutes, FifteenMinutes, ThirtyMinutes, OneHour, FourHour, OneDay, OneWeek, OneMonth, OneYear }

and
PeriodConverter.cs
protected override List<KeyValuePair<HuobiPeriod, string>> Mapping => new List<KeyValuePair<HuobiPeriod, string>> { new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.OneMinute, "1min"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.FiveMinutes, "5min"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.FifteenMinutes, "15min"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.ThirtyMinutes, "30min"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.OneHour, "60min"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.FourHour, "4hour"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.OneDay, "1day"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.OneWeek, "1week"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.OneMonth, "1mon"), new KeyValuePair<HuobiPeriod, string>(HuobiPeriod.OneYear, "1year") };

Error Serialized

Hello,

All placeOrder have to change long to long?
example:
Task<WebCallResult > PlaceOrderAsync(
to
Task<WebCallResult<long? > > PlaceOrderAsync(

Because Error Serialized if Huobi send an error message

Websocket doesnot support Proxy?

Here is the codes I used:

            var wsClient = new HuobiSocketClient(new HuobiSocketClientOptions()
            {
                ApiCredentials = new ApiCredentials(apiKey, apiSecret),
                Proxy = new ApiProxy("http://127.0.0.1", 8080);
            });


            await wsClient.SubscribeToOrderBookUpdatesAsync(PublicStatic.robotOptions.Symbol, 0, data =>
            {
                _logger.LogInformation($"[WS] Subscribe to order book updates");              
            });

Cannot subscribe to correct ticker

I'm experienced with binance and kucoin implementations, but trying to integrate Huobi.

client.SubscribeToSymbolTickerUpdatesAsync returns HuobiSymbolDatas and those tickers don't have ask/bids. I am not able to specify a coin name as the example here shows. Am I missing how to subscribe to specific tickers w/ ask/bid or is the wrapper missing it?

Wrong test for eventType in SubscribeToOrderUpdatesAsync

Hi JKorf,
with the latest version, you changed the code in the method SubscribeToOrderUpdatesAsync line 266 from:
var eventType = (string) data.Data["data"]["eventType"];

to
if (data.Data["data"] == null || data.Data["eventType"] == null)

Unfortunately, the eventType is not directely under Data.
I think the correct test is

          if (data.Data["data"] == null || data.Data["data"]["eventType"] == null)

Do you agree?

Eric

Signed Public Requests

Hi @JKorf

I had rate limit problems before, I got rate limit errors even I use proper limits. I talked with Huobi Technical Team and they recommended to use api keys even public data requests. I downloaded your huobi reposity and tried signed public requests. for example getklines. and woowww, it works.

I am sure many people suffer from this problem and they cant reach huobi technical team. Is it possible to add an option in huobiclientoptions as below
"If api credentials are exist, send signed requests for public endpoints"

Have a nice day.

Percentage Change

No percentage change in SubscribeToSymbolDetailUpdatesAsync
How can I get ?

GetOrdersAsync filters don't work

Hello!
I'm using Huobi. Net v1.0.1 and it seems like filters in method GetOrdersAsync don't work.

I have 2 orders in my history
id ...52783 and ...54950
Here is my code:
long? startOrderId = null; var lastHuobiResult = await client.GetOrdersAsync(symbol, Enum.GetValues(typeof(HuobiOrderState)).Cast<HuobiOrderState>(), null, null, null, startOrderId, limit);
when I'm setting startOrderId > firstHistoryOrder.Id: I'm getting first history order

Then I tried another approach:
DateTime startDate = DateTime.MinValue; DateTime finishDate = DateTime.MaxValue; var lastHuobiResult = await client.GetOrdersAsync(symbol, Enum.GetValues(typeof(HuobiOrderState)).Cast<HuobiOrderState>(), null, startDate, finishDate, null, limit);

I'm tying to set my startDate > than FinishedAt date of my first history order. And I'm also getting first history order. Even is my startDate grater then FinishedAt more than 100ms.

Is this issue related to library or to exchange?

Cant find subscription to liquidation websocket

Hi,
according to the api-doc, there is a liquidation websocket available.

Somehow i couldn't find the function to subscribe to that websocket, like i did in binance.net or bitmex.net :)
How is it working in here?

Kind regards and thanks in advance for help
Amannda

GetAccountHistoryAsync with transactionTypes error

I try to get account history filtered by transaction types. My request:var task = client.GetAccountHistoryAsync(acc.Id, startTime: DateTime.Now.AddDays(-30), transactionTypes: new List<HuobiTransactionType> { HuobiTransactionType.DepositWithdraw });.
As a result i've got a error: Server error: base-argument-type-enum-unsupported, base argument type unsupported {0}

HuobiBalanceType missing some types

about huobiclient ,when i call GetBalancesAsync I got an error:
Cannot map enum. Type: Huobi.Net.Objects.HuobiBalanceType, Value: loan
2019/06/27 21:59:24:916 | Error | Deserialize JsonSerializationException: Error setting value to 'Type' on 'Huobi.Net.Objects.HuobiBalance'.. Received data:
{
"status": "ok",
"data": {
"id": 3474679,
"type": "margin",
"state": "working",
"list": [
{
"currency": "btc",
"type": "trade",
"balance": "0.0000000062984"
},
{
"currency": "btc",
"type": "frozen",
"balance": "0"
},
{
"currency": "btc",
"type": "loan",
"balance": "0"
},
{
"currency": "btc",
"type": "interest",
"balance": "0"
},

the type include loan and interest
Maybe you should add these two types to the HuobiBalanceType .

Strange Behavior when using request from SocketClient

Hi there,

First I'd like to cheer for the great work done.

When sending a request trough the SocketClient, if I get a ping message from Huobi before the message itself from the request, the variable "result.Data" return null.

Is there any treatment I can do in order to avoid that ?

Best Regards,

Api Access Error

I Get this error when i try to access authenticated endpoints.
Server error: api-signature-not-valid, Signature not valid: Incorrect Access key [Access key错误]
my Api Key and secret key is correct.

force to reconnet websocket client?

for some reasons, i hope to reconnect the websocket client…… is there a quick way to implement such a function rather than close and resubscribe?

next-time field missing from result of GetHistoryOrdersAsync

Hi @JKorf ,
the GetHistoryOrdersAsync api returns an IEnumerable of HuobiOrder. But for pagination purpose, a next-time is also returned by the server, when the query return to much data. Unfortunately, this field is not part of the data field, but after.
Here a sample : {"status":"ok","data":[{"id":180316741408065,"symbol":"zenbtc","account-id":12156447,"client-order-id":"","amount":"4.760000000000000000","price":"0.000419830000000000","created-at":1609685999833,"type":"sell-limit","field-amount":"0.0","field-cash-amount":"0.0","field-fees":"0.0","finished-at":1609686002967,"source":"spot-api","state":"canceled","canceled-at":1609686002959}, .... ],"next-time":1609684257688}.
What is the best way to implement this?
I can change the return value of the API to return an object with this field and an IEnumerable. Something like GetTickersAsync
Do you have a better idea?

Thanks.
Eric

Huobi api updates (orders call)

Hi!
Accordingly to recent Huobi updates there are several problems:

  1. In order/orders api call parameter symbol is not required any more. In official api docs this parameter is set as required, but if you'll look at the site there are call to orders/orders without symbol. Screenshot:
    image
    It's also tested by me. This api call works without symbol.
  2. In orders/orders api call parameter state doesn't work correctly any more. If I set only Filled or only Canceled state it works as expected. But if I set Filled, Canceled and any other state as array, the call will response only with Filled orders. Maybe this problem is caused by encoding comma separator to hexadecimal value but I'm not shure.
  3. Accordingly to changelog message from 2019.04.29 20:30 there are new endpoint for history orders order/history. Would be nice to have it in library. Also order/orders seems to be deprecated in the future.

One or more errors occurred.?

I got the following error message with these codes:

    var socketClient = new HuobiSocketClient();
            // HuobiSocketClient.SetDefaultOptions(new HuobiSocketClientOptions() { ApiCredentials = new ApiCredentials("", ""), });
            Console.WriteLine(socketClient.BaseAddress);
            socketClient.SubscribeToMarketKlineUpdates("btcusdt", HuobiPeriod.FiveMinutes, data =>
            {
                Console.WriteLine("Received kline update. Last price: " + data.Close);
            });

System.AggregateException
HResult=0x80131500
Message=One or more errors occurred.
Source=System.Private.CoreLib
StackTrace:
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at Huobi.Net.HuobiSocketClient.SubscribeToMarketKlineUpdates(String symbol, HuobiPeriod period, Action1 onData) in K:\Huobi.Net-master\Huobi.Net-master\Huobi.Net\HuobiSocketClient.cs:line 93
at ConsoleApp1.Program.Main(String[] args) in K:\Huobi.Net-master\Huobi.Net-master\ConsoleApp1\Program.cs:line 15

内部异常 1:
AggregateException: One or more errors occurred.

内部异常 2:
NullReferenceException: Object reference not set to an instance of an object.

any idea? thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.