### Spot Quickstart Example Source: https://github.com/jkorf/htx.net/blob/master/llms.txt Demonstrates basic client setup, fetching ticker and account information, placing a limit order, and checking order status. Requires client initialization. ```csharp var client = new HtxClient(); // Get ticker var ticker = await client.SpotApi.ExchangeData.GetTickerAsync("btcusdt"); Console.WriteLine($"BTCUSDT Ticker: {ticker.Data.LastPrice}"); // Get account id and balances var accountId = await client.SpotApi.Account.GetAccountIdAsync(); var balances = await client.SpotApi.Account.GetBalancesAsync(accountId.Data); Console.WriteLine($"Balances: {balances.Data.Count}"); // Place a limit order var order = await client.SpotApi.Order.PlaceOrderAsync("btcusdt", OrderSide.Buy, OrderType.Limit, 10000m, 0.001m); Console.WriteLine($"Order placed: {order.Data.OrderId}"); // Check order status var orderStatus = await client.SpotApi.Order.GetOrderAsync(order.Data.OrderId, "btcusdt"); Console.WriteLine($"Order status: {orderStatus.Data.Status}"); await client.DisposeAsync(); ``` -------------------------------- ### Running HTX.Net Examples Source: https://github.com/jkorf/htx.net/blob/master/Examples/ai-friendly/README.md Instructions on how to set up a new .NET console project, add the HTX.Net package, and run the provided examples. Remember to replace placeholder API keys with your actual credentials. ```bash dotnet new console -n MyHtxApp cd MyHtxApp dotnet add package JKorf.HTX.Net # Copy the example .cs file content into Program.cs # Replace API_KEY / API_SECRET placeholders with your own dotnet run ``` -------------------------------- ### Basic REST Request: Get Ticker Source: https://github.com/jkorf/htx.net/blob/master/README.md Example of how to instantiate the REST client and retrieve the ticker information for ETH/USDT. ```csharp // 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; ``` -------------------------------- ### USDT Futures Trading Example Source: https://github.com/jkorf/htx.net/blob/master/llms.txt Illustrates USDT futures trading, including setting cross margin with leverage, placing a market order, retrieving position details, and closing a position. Ensure proper API key setup for futures trading. ```csharp var client = new HtxClient(); // Set cross margin with leverage await client.UsdtFuturesApi.Margin.SetMarginModeAsync("BTC-USD", FuturesMarginMode.Cross, 10); // Place a market order var order = await client.UsdtFuturesApi.Order.PlaceOrderAsync("BTC-USD", OrderSide.Buy, OrderType.Market, 0.001m); Console.WriteLine($"Market order placed: {order.Data.OrderId}"); // Get position var position = await client.UsdtFuturesApi.Position.GetPositionAsync("BTC-USD"); Console.WriteLine($"Position size: {position.Data.LeveragedNotional}"); // Close position var close = await client.UsdtFuturesApi.Position.ClosePositionAsync("BTC-USD"); Console.WriteLine($"Position closed: {close.Data.Success}"); await client.DisposeAsync(); ``` -------------------------------- ### Place Multiple Orders Request Example Source: https://github.com/jkorf/htx.net/blob/master/HTX.Net.UnitTests/Endpoints/Spot/Trading/PlaceMultipleOrder.txt This example demonstrates how to construct a POST request to the \/v1\/order\/batch-orders endpoint to place multiple orders. It shows the expected request body format. ```json POST /v1/order/batch-orders true { "status": "ok", "data": [ { "order-id": 361560582529749, "client-order-id": "2345" }, { "client-order-id": "23456", "err-code": "order-value-min-error", "err-msg": "Order total cannot be lower than: 5 USDT" } ] } ``` -------------------------------- ### Get Cross Margin Assets - Request Example Source: https://github.com/jkorf/htx.net/blob/master/HTX.Net.UnitTests/Endpoints/UsdtMarginSwap/SubAccount/GetCrossMarginAssets.txt This example demonstrates how to make a POST request to the /linear-swap-api/v1/swap_cross_sub_account_list endpoint to retrieve cross margin asset information for sub-accounts. ```http POST /linear-swap-api/v1/swap_cross_sub_account_list true ``` -------------------------------- ### Get Assets Async Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Retrieves a list of all supported currencies on the Huobi exchange. Use this to get a general overview of available assets. ```C# Task>> GetAssetsAsync([Optional] CancellationToken ct); ``` -------------------------------- ### Get Market Data Source: https://github.com/jkorf/htx.net/wiki/Usage Examples of how to retrieve various types of market data, including symbol information, tickers, order books, and recent trades. ```APIDOC ## Get Market Data This section provides examples for fetching market data using the `HuobiClient`. ### Getting Info on All Symbols ```csharp // Getting info on all symbols var symbolData = await huobiClient.SpotApi.ExchangeData.GetSymbolsAsync(); ``` ### Getting Tickers for All Symbols ```csharp // Getting tickers for all symbols var tickerData = await huobiClient.SpotApi.ExchangeData.GetTickersAsync(); ``` ### Getting the Order Book of a Symbol ```csharp // Getting the order book of a symbol var orderBookData = await huobiClient.SpotApi.ExchangeData.GetOrderBookAsync("BTC-USDT", 0); ``` ### Getting Recent Trades of a Symbol ```csharp // Getting recent trades of a symbol var tradeHistoryData = await huobiClient.SpotApi.ExchangeData.GetTradeHistoryAsync("BTC-USDT"); ``` ``` -------------------------------- ### Create and Manage USDT-M Futures Order Book with HTXOrderBookFactory Source: https://context7.com/jkorf/htx.net/llms.txt Use HTXOrderBookFactory to create a USDT-M futures order book. Start and stop the futures book asynchronously. Access the best bid price after starting. ```csharp // ---- Futures order book ---- var futuresBook = factory.CreateUsdtFutures("ETH-USDT"); await futuresBook.StartAsync(); Console.WriteLine($"Futures best bid: {futuresBook.BestBid?.Price}"); await futuresBook.StopAsync(); ``` -------------------------------- ### REST Client Setup Source: https://github.com/jkorf/htx.net/blob/master/AGENTS.md Demonstrates how to set up the HTXRestClient for authenticated and unauthenticated access. ```APIDOC ## REST Client Setup Always create the client via `HTXRestClient`. For trading, configure credentials. ```csharp using HTX.Net; using HTX.Net.Clients; var restClient = new HTXRestClient(options => { options.ApiCredentials = new HTXCredentials("API_KEY", "API_SECRET"); }); ``` For read-only public market data, credentials are not required: ```csharp var publicClient = new HTXRestClient(); ``` ``` -------------------------------- ### Get Cross Margin Assets - Response Example Source: https://github.com/jkorf/htx.net/blob/master/HTX.Net.UnitTests/Endpoints/UsdtMarginSwap/SubAccount/GetCrossMarginAssets.txt This is a sample response for the cross margin assets query, showing the status, data including sub-account details, and a timestamp. ```json { "status": "ok", "data": [ { "sub_uid": 123456789, "list": [ { "margin_balance": 163.56170812955912, "risk_rate": 78.89672939225149, "margin_asset": "USDT", "margin_mode": "cross", "margin_account": "USDT" } ] } ], "ts": 1606962745633 } ``` -------------------------------- ### Get HTX Server Time Source: https://context7.com/jkorf/htx.net/llms.txt Retrieves the current server time from HTX. No specific setup is required beyond initializing the client. ```csharp using HTX.Net.Clients; var client = new HTXRestClient(); // ---- Server time ---- var time = await client.SpotApi.ExchangeData.GetServerTimeAsync(); Console.WriteLine($ ``` -------------------------------- ### Creating Huobi Clients Source: https://github.com/jkorf/htx.net/wiki/Usage Demonstrates how to create instances of HuobiClient and HuobiSocketClient, with examples of setting various options and default options. ```APIDOC ## Creating Huobi Clients There are two primary clients available for interacting with the Huobi API: `HuobiClient` for RESTful requests and `HuobiSocketClient` for real-time WebSocket communication. ### Creating a REST Client ```csharp var huobiClient = new HuobiClient(new HuobiClientOptions() { // Set options here for this client }); ``` ### Creating a WebSocket Client ```csharp var huobiSocketClient = new HuobiSocketClient(new HuobiSocketClientOptions() { // Set options here for this client }); ``` ### Client Options Various options can be configured for the clients. Here's an example demonstrating API credentials, log level, and request timeout: ```csharp var huobiClient = new HuobiClient(new HuobiClientOptions() { ApiCredentials = new ApiCredentials("API-KEY", "API-SECRET"), LogLevel = LogLevel.Trace, RequestTimeout = TimeSpan.FromSeconds(60) }); ``` ### Setting Default Options Alternatively, you can set default options that will be applied to all newly created clients: ```csharp HuobiClient.SetDefaultOptions(new HuobiClientOptions{ // Set options here for all new clients }); var huobiClient = new HuobiClient(); ``` For more detailed information on specific options, refer to the [CryptoExchange.Net wiki](https://github.com/JKorf/CryptoExchange.Net/wiki/Options). ### Dependency Injection Information regarding dependency injection setup can be found on the [CryptoExchange.Net wiki](https://github.com/JKorf/CryptoExchange.Net/wiki/Clients#dependency-injection). ``` -------------------------------- ### Initialize HTXRestClient for Live Environment Source: https://github.com/jkorf/htx.net/blob/master/AGENTS.md Create an HTXRestClient instance configured for the live trading environment. ```csharp using HTX.Net; var live = new HTXRestClient(o => o.Environment = HTXEnvironment.Live); ``` -------------------------------- ### Get Spot Ticker using Shared APIs Source: https://github.com/jkorf/htx.net/blob/master/AGENTS.md Utilize the unified shared interfaces from CryptoExchange.Net for exchange-agnostic code. This example retrieves a spot ticker for ETHUSDT. ```csharp using HTX.Net.Clients; using CryptoExchange.Net.SharedApis; var htxShared = new HTXRestClient().SpotApi.SharedClient; var symbol = new SharedSymbol(TradingMode.Spot, "ETH", "USDT"); var ticker = await htxShared.GetSpotTickerAsync(new GetTickerRequest(symbol)); ``` -------------------------------- ### Dependency Injection Setup Source: https://github.com/jkorf/htx.net/blob/master/docs/ai-api-map.md Register HTX services with dependency injection. Configure client options within the lambda. ```csharp services.AddHTX(options => { ... }) ``` -------------------------------- ### Dependency Injection Setup Source: https://github.com/jkorf/htx.net/blob/master/llms-full.txt Configure HTX.Net clients for dependency injection, including API credentials. ```csharp services.AddHTX(options => { options.Rest.ApiCredentials = new HTXCredentials("API_KEY", "API_SECRET"); options.Socket.ApiCredentials = new HTXCredentials("API_KEY", "API_SECRET"); }); ``` -------------------------------- ### Get Closed Spot Orders Source: https://context7.com/jkorf/htx.net/llms.txt Retrieves a list of closed spot orders within a specified time range. Requires a symbol and can be filtered by start time and a result limit. ```csharp // ---- Get closed orders ---- var closedOrders = await client.SpotApi.Trading.GetClosedOrdersAsync( symbol: "ETHUSDT", startTime: DateTime.UtcNow.AddDays(-1), limit: 100); ``` -------------------------------- ### Place Spot Orders (Limit, Market, Stop-Limit) Source: https://context7.com/jkorf/htx.net/llms.txt Demonstrates placing different types of spot orders. Ensure you have retrieved the account ID first. Price is not required for market orders. ```csharp using HTX.Net.Clients; using HTX.Net.Enums; var client = new HTXRestClient(o => o.ApiCredentials = new HTXCredentials("KEY", "SECRET")); // Retrieve the spot account id first (required for order placement) var accounts = await client.SpotApi.Account.GetAccountsAsync(); var accountId = accounts.Data.First(a => a.Type == AccountType.Spot).Id; // ---- Place limit buy order ---- var limitOrder = await client.SpotApi.Trading.PlaceOrderAsync( accountId: accountId, symbol: "ETHUSDT", side: OrderSide.Buy, type: OrderType.Limit, quantity: 0.01m, price: 2000m, clientOrderId: "my-order-001"); if (!limitOrder.Success) { Console.WriteLine($"Error {limitOrder.Error?.Code}: {limitOrder.Error?.Message}"); return; } Console.WriteLine($"Placed order: {limitOrder.Data}"); // ---- Place market sell order ---- var marketOrder = await client.SpotApi.Trading.PlaceOrderAsync( accountId: accountId, symbol: "ETHUSDT", side: OrderSide.Sell, type: OrderType.Market, quantity: 0.01m); // price not required for market orders // ---- Place stop-limit order ---- var stopOrder = await client.SpotApi.Trading.PlaceOrderAsync( accountId: accountId, symbol: "ETHUSDT", side: OrderSide.Sell, type: OrderType.StopLimit, quantity: 0.01m, price: 1900m, stopPrice: 1950m, stopOperator: Operator.LesserThanOrEqual); ``` -------------------------------- ### Get Withdraw Deposit Async Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiAccount Searches for existing withdraws and deposits, returning their latest status. Requires specifying the type of transaction (withdraw or deposit) and can be filtered by asset, starting ID, size, and direction. An optional cancellation token can be provided. ```C# Task>> GetWithdrawDepositAsync(WithdrawDepositType type, [Optional] string? asset, [Optional] int? from, [Optional] int? size, [Optional] FilterDirection? direction, [Optional] CancellationToken ct); ``` -------------------------------- ### HTX.Net Client Initialization Source: https://github.com/jkorf/htx.net/blob/master/llms-full.txt Use HTXRestClient for new projects instead of the legacy HuobiClient. ```csharp var client = new HTXRestClient(); ``` -------------------------------- ### Setup HTX REST Client with Credentials Source: https://github.com/jkorf/htx.net/blob/master/AGENTS.md Instantiate the HTXRestClient with API credentials for authenticated requests. Ensure your API key and secret are correctly provided. ```csharp using HTX.Net; using HTX.Net.Clients; var restClient = new HTXRestClient(options => { options.ApiCredentials = new HTXCredentials("API_KEY", "API_SECRET"); }); ``` -------------------------------- ### Get Symbol Details Async Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiSocketClientSpotStreams Retrieves detailed information for a specific trading symbol. Use this to get metadata about a symbol. ```C# Task> GetSymbolDetailsAsync(string symbol); ``` -------------------------------- ### Get Klines Data Async Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiSocketClientSpotStreams Retrieves candlestick data for a specified symbol and period. Use this to get historical price movements. ```C# Task>> GetKlinesAsync(string symbol, KlineInterval period); ``` -------------------------------- ### Create and Manage Spot Order Book with HTXOrderBookFactory Source: https://context7.com/jkorf/htx.net/llms.txt Instantiate HTXOrderBookFactory to create and manage a live-synced spot order book. Subscribe to status and best offer changes, then start and stop the book asynchronously. Check book depth and best bid/ask prices. ```csharp using HTX.Net; using HTX.Net.SymbolOrderBooks; // ---- Direct factory instantiation ---- var factory = new HTXOrderBookFactory(); var spotBook = factory.CreateSpot("ETHUSDT"); spotBook.OnStatusChange += (old, current) => Console.WriteLine($"Book status: {old} → {current}"); spotBook.OnBestOffersChanged += (bid, ask) => Console.WriteLine($"Best: {bid.Price} / {ask.Price}"); await spotBook.StartAsync(); // Order book is now live-synced Console.WriteLine($"Best bid: {spotBook.BestBid?.Price}, best ask: {spotBook.BestAsk?.Price}"); Console.WriteLine($"Bid depth: {spotBook.Bids.Count()}, ask depth: {spotBook.Asks.Count()}"); await spotBook.StopAsync(); ``` -------------------------------- ### WebSocket Streams Example Source: https://github.com/jkorf/htx.net/blob/master/llms.txt Shows how to subscribe to real-time WebSocket streams for tickers, klines, and account/order updates. Includes proper teardown procedures to close connections gracefully. ```csharp var client = new HtxSocketClient(); // Subscribe to ticker stream await client.SpotApi.SubscribeToTradeUpdatesAsync("btcusdt", data => { Console.WriteLine($"Trade: {data.Data.Price}"); }); // Subscribe to kline stream await client.SpotApi.SubscribeToKlineUpdatesAsync("btcusdt", KlineInterval.OneMinute, data => { Console.WriteLine($"Kline: {data.Data.ClosePrice}"); }); // Subscribe to account updates await client.SpotApi.SubscribeToAccountUpdatesAsync(data => { Console.WriteLine($"Account update: {data.Data.Balance}"); }); // Keep alive Console.ReadKey(); await client.DisposeAsync(); ``` -------------------------------- ### Get All Tickers Source: https://github.com/jkorf/htx.net/blob/master/HTX.Net.UnitTests/Endpoints/Spot/ExchangeData/GetTickers.txt Fetches a list of all available tickers on the spot exchange. This endpoint is useful for getting a quick overview of market activity. ```APIDOC ## GET /market/tickers ### Description Retrieves a list of all tickers available on the spot exchange. This includes trading symbols, price information, and volume data. ### Method GET ### Endpoint /market/tickers ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request, e.g., "ok". - **ts** (integer) - Timestamp of the response in milliseconds. - **data** (array) - An array of ticker objects. - **symbol** (string) - The trading pair symbol (e.g., "smtusdt"). - **open** (number) - The opening price for the trading period. - **high** (number) - The highest price during the trading period. - **low** (number) - The lowest price during the trading period. - **close** (number) - The closing price for the trading period. - **amount** (number) - The total trading volume in quote currency. - **vol** (number) - The total trading volume in base currency. - **count** (integer) - The number of trades. - **bid** (number) - The current best bid price. - **bidSize** (number) - The size of the current best bid. - **ask** (number) - The current best ask price. - **askSize** (number) - The size of the current best ask. #### Response Example ```json { "status": "ok", "ts": 1629789355531, "data": [ { "symbol": "smtusdt", "open": 0.004659, "high": 0.004696, "low": 0.0046, "close": 0.00468, "amount": 36551302.17544405, "vol": 170526.0643855023, "count": 1709, "bid": 0.004651, "bidSize": 54300.341, "ask": 0.004679, "askSize": 1923.4879 }, { "symbol": "ltcht", "open": 12.795626, "high": 12.918053, "low": 12.568926, "close": 12.918053, "amount": 1131.801675005825, "vol": 14506.9381937385, "count": 923, "bid": 12.912687, "bidSize": 0.1068, "ask": 12.927032, "askSize": 5.3228 } ] } ``` ``` -------------------------------- ### Place Order Async C# Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiTrading Places a new order on the Huobi Spot market. Requires account ID, symbol, side, type, and quantity. Optional parameters include price, client order ID, and stop-loss/take-profit details. ```csharp Task> PlaceOrderAsync(long accountId, string symbol, OrderSide side, OrderType type, decimal quantity, [Optional] decimal? price, [Optional] string? clientOrderId, [Optional] SourceType? source, [Optional] decimal? stopPrice, [Optional] Operator? stopOperator, [Optional] CancellationToken ct); ``` -------------------------------- ### Get Spot Account Balances Source: https://github.com/jkorf/htx.net/blob/master/docs/index.html Retrieves the asset balances for a spot account. Requires API credentials for authentication. You must first get the account ID. ```csharp var htxClient = new HTXRestClient(options => { options.ApiCredentials = new ApiCredentials("KEY", "SECRET"); }); // First need to get the id of the account to get balances for var accounts = await htxClient.SpotApi.Account.GetAccountsAsync(); var spotAccountId = accounts.Data.Single(d => d.Type == HTX.Net.Enums.AccountType.Spot).Id; var result = await htxClient.SpotApi.Account.GetBalancesAsync(spotAccountId); ``` -------------------------------- ### Placing a Spot Order Source: https://github.com/jkorf/htx.net/blob/master/AGENTS.md Illustrates how to place a limit order on the spot market. ```APIDOC ## Core Pattern: Placing a Spot Order Spot symbols use no separator, for example `ETHUSDT`. ```csharp using HTX.Net.Enums; var order = await restClient.SpotApi.Trading.PlaceOrderAsync( accountId: accountId, symbol: "ETHUSDT", side: OrderSide.Buy, type: OrderType.Limit, quantity: 0.01m, price: 1000m); if (!order.Success) { Console.WriteLine(order.Error); return; } var orderId = order.Data; ``` ``` -------------------------------- ### Environment Configuration Source: https://github.com/jkorf/htx.net/blob/master/llms-full.txt Configure the client to use the live environment or a custom environment with specific addresses. ```csharp var live = new HTXRestClient(options => options.Environment = HTXEnvironment.Live); var custom = HTXEnvironment.CreateCustom( "custom", restAddress: "https://api.example.com", socketAddress: "wss://api.example.com/ws", usdtMarginSwapRestAddress: "https://swap.example.com", usdtMarginSwapSocketAddress: "wss://swap.example.com/ws"); ``` -------------------------------- ### Placing and Managing Orders Source: https://github.com/jkorf/htx.net/wiki/Usage Guides on placing various types of orders (limit, market, stop-limit), retrieving specific orders, order history, and canceling orders. ```APIDOC ## Placing and Managing Orders ### Placing an Order Examples for placing different types of orders: **Placing a Buy Limit Order:** ```csharp // Placing a buy limit order for 0.001 BTC at a price of 50000USDT each var orderData = await huobiClient.SpotApi.Trading.PlaceOrderAsync( accountId, "BTC-USDT", OrderSide.Buy, OrderType.Limit, 0.001m, 50000); ``` **Placing a Market Buy Order:** *Note: Buy market orders specify the quantity in quote currency (e.g., USDT). ```csharp // Placing a market buy order for 50USDT. Buy market orders specify the quantity in quote quantity var orderData = await huobiClient.SpotApi.Trading.PlaceOrderAsync( accountId, "BTC-USDT", OrderSide.Buy, OrderType.Market, 50); ``` **Placing a Stop Limit Order:** ```csharp // Place a stop loss order, place a limit order of 0.001 BTC at 39000USDT each when the last trade price drops below 40000USDT var orderData = await huobiClient.SpotApi.Trading.PlaceOrderAsync( accountId, "BTC-USDT", OrderSide.Sell, OrderType.StopLimit, 0.001m, 39000, stopPrice: 40000, stopOperator: Operator.LesserThanOrEqual); ``` ### Requesting a Specific Order ```csharp // Request info on order with id `1234` var orderData = await huobiClient.SpotApi.Trading.GetOrderAsync(1234); ``` ### Requesting Order History ```csharp // Get all orders conform the parameters var ordersData = await huobiClient.SpotApi.Trading.GetClosedOrdersAsync("btcusdt"); ``` ### Cancel Order ```csharp // Cancel order with id `1234` var orderData = await huobiClient.SpotApi.Trading.CancelOrderAsync(1234); ``` ### Get User Trades ```csharp var userTradesResult = await huobiClient.SpotApi.Trading.GetUserTradesAsync(); ``` ``` -------------------------------- ### GetSymbolStatusAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Gets the market status for all symbols on Huobi. ```APIDOC ## GetSymbolStatusAsync ### Description Gets the market status. ### Method GET ### Endpoint /market/status ### Response #### Success Response (200) - **data** (HuobiSymbolStatus) - Object containing the market status for symbols ### Response Example ```json { "status": "ok", "data": { "symbols": [ { "symbol": "btcusdt", "status": "trading" } ] } } ``` ``` -------------------------------- ### GetServerTimeAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Gets the current server time from Huobi. ```APIDOC ## GetServerTimeAsync ### Description Gets the server time. ### Method GET ### Endpoint /v1/common/timestamp ### Response #### Success Response (200) - **data** (long) - Server timestamp in milliseconds ### Response Example ```json { "status": "ok", "data": 1574779800000 } ``` ``` -------------------------------- ### Use HTX Shared REST and Socket Clients Source: https://context7.com/jkorf/htx.net/llms.txt Demonstrates using shared clients for spot and futures tickers, placing orders, and managing balances. Also shows how to subscribe to ticker and order book streams via shared socket clients. ```csharp using CryptoExchange.Net.SharedApis; using HTX.Net.Clients; // ---- Shared REST client — spot ticker ---- ISpotTickerRestClient htxSpotShared = new HTXRestClient().SpotApi.SharedClient; var ethSymbol = new SharedSymbol(TradingMode.Spot, "ETH", "USDT"); var ticker = await htxSpotShared.GetSpotTickerAsync(new GetTickerRequest(ethSymbol)); Console.WriteLine($"[{ticker.Data.Exchange}] ETH/USDT: {ticker.Data.LastPrice}"); // ---- Shared REST client — futures ticker ---- IFuturesTickerRestClient htxFuturesShared = new HTXRestClient().UsdtFuturesApi.SharedClient; var futSymbol = new SharedSymbol(TradingMode.PerpetualLinear, "ETH", "USDT"); var ftTicker = await htxFuturesShared.GetFuturesTickerAsync(new GetTickerRequest(futSymbol)); // ---- Shared REST client — place spot order ---- ISpotOrderRestClient spotOrderShared = new HTXRestClient(o => o.ApiCredentials = new HTXCredentials("KEY", "SECRET")) .SpotApi.SharedClient; var orderResult = await spotOrderShared.PlaceSpotOrderAsync(new PlaceSpotOrderRequest( ethSymbol, SharedOrderSide.Buy, SharedOrderType.Limit, quantity: 0.01m, price: 2000m)); // ---- Shared REST client — balance ---- IBalanceRestClient balShared = new HTXRestClient(o => o.ApiCredentials = new HTXCredentials("KEY", "SECRET")) .SpotApi.SharedClient; var balances = await balShared.GetBalancesAsync(new GetBalancesRequest()); // ---- Shared socket client — ticker stream ---- var socketClient = new HTXSocketClient(); ITickerSocketClient tickerSocket = socketClient.SpotApi.SharedClient; var sub = await tickerSocket.SubscribeToTickerUpdatesAsync( new SubscribeTickerRequest(ethSymbol), update => Console.WriteLine($"[{tickerSocket.Exchange}] {update.Data.LastPrice}")); Console.ReadLine(); // Always unsubscribe through the concrete socket client await socketClient.UnsubscribeAsync(sub.Data); // ---- Shared order book socket ---- IOrderBookSocketClient bookSocket = socketClient.SpotApi.SharedClient; var bookSub = await bookSocket.SubscribeToOrderBookUpdatesAsync( new SubscribeOrderBookRequest(ethSymbol, 20), update => Console.WriteLine($"Bids: {update.Data.Bids.First().Price}")); ``` -------------------------------- ### GetLastTradeAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Gets the last trade for a specified symbol. ```APIDOC ## GetLastTradeAsync ### Description Gets the last trade for a symbol. ### Method GET ### Endpoint /market/trade ### Parameters #### Query Parameters - **symbol** (string) - Required - The symbol to request for ### Response #### Success Response (200) - **tick** (HuobiSymbolTrade) - Object containing the last trade details ### Response Example ```json { "ch": "market.btcusdt.trade.detail", "status": "ok", "ts": 1574779800000, "tick": { "id": 2345678901, "ts": 1574779799000, "data": [ { "price": 7165.000000000000000000, "amount": 0.000000000000000000, "direction": "sell", "id": 1234567890, "ts": 1574779799000 } ] } } ``` ``` -------------------------------- ### Create Huobi REST Client Source: https://github.com/jkorf/htx.net/wiki/Usage Instantiate a new `HuobiClient` to interact with the Huobi REST API. Options can be configured during initialization. ```C# var huobiClient = new HuobiClient(new HuobiClientOptions() { // Set options here for this client }); ``` -------------------------------- ### Multi-Exchange Pattern Example Source: https://github.com/jkorf/htx.net/blob/master/llms.txt Demonstrates using CryptoExchange.Net's SharedApis for writing exchange-agnostic code. This allows for unified access to common functionalities across different exchange clients. ```csharp var clients = new List() { new HtxClient(), // Add other exchange clients here }; var sharedApi = new CryptoExchange.Net.Clients.SharedApi(clients); // Get ticker across all exchanges var tickers = await sharedApi.GetAllTickersAsync("btcusdt"); foreach (var ticker in tickers) { Console.WriteLine($"{ticker.Exchange}: {ticker.Price}"); } await Task.WhenAll(clients.Select(c => c.DisposeAsync())); ``` -------------------------------- ### Get Order Source: https://context7.com/jkorf/htx.net/llms.txt Retrieves details of a specific spot order. ```APIDOC ## Get Order ### Description Retrieves details of a specific spot order using its ID. ### Method GET ### Endpoint /api/v1/order/orders/{orderId} ### Parameters #### Path Parameters - **orderId** (long) - Required - The ID of the order to retrieve. #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **Data** (object) - Contains the order details, including status and filled quantity. - **Success** (boolean) - Indicates if the operation was successful. #### Response Example ```json { "data": { "orderId": 123456789, "symbol": "ETHUSDT", "status": "PartFilled", "quantityFilled": 0.005 }, "success": true } ``` ``` -------------------------------- ### Initialize HTXRestClient Source: https://github.com/jkorf/htx.net/blob/master/docs/ai-api-map.md Use this to make REST calls to the HTX API. Instantiate with default or custom options. ```csharp new HTXRestClient() ``` -------------------------------- ### GetSymbolDetails24HAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Gets the 24-hour market statistics for a specified symbol. ```APIDOC ## GetSymbolDetails24HAsync ### Description Gets 24h stats for a symbol. ### Method GET ### Endpoint /market/detail/24h ### Parameters #### Query Parameters - **symbol** (string) - Required - The symbol to get the data for ### Response #### Success Response (200) - **data** (array) - List of HuobiSymbolDetails objects ### Response Example ```json { "ch": "market.btcusdt.detail", "status": "ok", "ts": 1574779800000, "tick": { "symbol": "btcusdt", "open": 7165.000000000000000000, "close": 7165.000000000000000000, "low": 7165.000000000000000000, "high": 7165.000000000000000000, "amount": 0.000000000000000000, "count": 0.000000000000000000, "vol": 0.000000000000000000, "bid": [7165.000000000000000000, 0.000000000000000000], "ask": [7165.010000000000000000, 0.000000000000000000], "lastPrice": 7165.000000000000000000, "lastQty": 0.000000000000000000, "highestBid": 7165.000000000000000000, "lowestAsk": 7165.010000000000000000, "change": "0.00%" } } ``` ``` -------------------------------- ### GetKlinesAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Get candlestick data for a specified symbol and period. ```APIDOC ## GetKlinesAsync ### Description Get candlestick data for a symbol. ### Method GET ### Endpoint /market/history/kline ### Parameters #### Query Parameters - **symbol** (string) - Required - The symbol to get the data for - **period** (KlineInterval) - Required - The period of a single candlestick (e.g., 1min, 5min, 1day) - **limit** (int) - Optional - The amount of candlesticks to retrieve ### Response #### Success Response (200) - **data** (array) - List of HuobiKline objects ### Response Example ```json { "ch": "market.btcusdt.kline.1min", "status": "ok", "ts": 1489059800000, "mப்பான": false, "data": [ { "id": 1489059800, "count": 1000, "open": 7165.000000000000000000, "close": 7165.000000000000000000, "low": 7165.000000000000000000, "high": 7165.000000000000000000, "amount": 0.000000000000000000, "count": 0.000000000000000000, "vol": 0.000000000000000000 } ] } ``` ``` -------------------------------- ### Create Huobi Socket Client Source: https://github.com/jkorf/htx.net/wiki/Usage Instantiate a new `HuobiSocketClient` to subscribe to real-time data streams from Huobi. Options can be configured during initialization. ```C# var huobiSocketClient = new HuobiSocketClient(new HuobiSocketClientOptions() { // Set options here for this client }); ``` -------------------------------- ### GetAssetsAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Gets a list of supported currencies on the Huobi exchange. ```APIDOC ## GetAssetsAsync ### Description Gets a list of supported currencies. ### Method GET ### Endpoint /v2/reference/currency ### Response #### Success Response (200) - **data** (array) - List of strings representing supported currencies ### Response Example ```json { "status": "ok", "data": [ "usdt", "btc", "eth" ] } ``` ``` -------------------------------- ### GetSubAccountBalancesAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiAccount Gets a list of balances for a specific sub account. ```APIDOC ## GetSubAccountBalancesAsync ### Description Gets a list of balances for a specific sub account. ### Method GET ### Endpoint /v1/sub-user/balances ### Parameters #### Query Parameters - **subAccountId** (long) - Required - The id of the sub account to get the balances for - **ct** (CancellationToken) - Optional - Cancellation token ### Response #### Success Response (200) - **data** (IEnumerable) - A list of balances for the sub account. ### Response Example ```json { "data": [ { "currency": "usdt", "type": "trade", "balance": "100.00000000" } ] } ``` ``` -------------------------------- ### Install HTX.Net Package Source: https://github.com/jkorf/htx.net/blob/master/AGENTS.md Use the dotnet CLI to add the HTX.Net package to your project. This package supports multiple .NET target frameworks and Native AOT. ```bash dotnet add package JKorf.HTX.Net ``` -------------------------------- ### Get Futures Contracts Source: https://github.com/jkorf/htx.net/blob/master/llms-full.txt Retrieves a list of available futures contracts. ```APIDOC ## GET /api/v1/usdt-futures/contracts ### Description Retrieves a list of available futures contracts. ### Method GET ### Endpoint /api/v1/usdt-futures/contracts ### Parameters #### Query Parameters - **contractType** (string) - Optional - The type of contract (e.g., "this_week", "next_week", "quarter", "next_quarter"). ### Response #### Success Response (200) - **contracts** (array of objects) - A list of futures contract information. - **contractCode** (string) - The code of the contract (e.g., "ETH-USDT"). - **symbol** (string) - The trading pair symbol. - **priceTick** (decimal) - The minimum price change. ### Request Example ```csharp var result = await client.UsdtFuturesApi.ExchangeData.GetContractsAsync(ContractType.NextWeek); ``` ``` -------------------------------- ### GetDepositAddressesAsync C# Example Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiAccount Queries the deposit addresses for a given asset. This is useful for initiating deposits to your Huobi account. ```csharp Task>> GetDepositAddressesAsync(string asset, [Optional] CancellationToken ct); ``` -------------------------------- ### Get Symbols Source: https://github.com/jkorf/htx.net/blob/master/docs/index.html Retrieves a list of supported spot trading symbols. ```APIDOC ## Get Symbols ### Description Get a list of supported spot symbols. ### Method ```csharp var result = await htxClient.SpotApi.ExchangeData.GetSymbolsAsync(); ``` ``` -------------------------------- ### PlaceOrderAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiTrading Places a new order on the Huobi Spot market. ```APIDOC ## PlaceOrderAsync ### Description Places a new order on the Huobi Spot market. ### Method APIDOC ### Endpoint APIDOC ### Parameters #### Path Parameters - **accountId** (long) - Required - The account to place the order for - **symbol** (string) - Required - The symbol to place the order for - **side** (OrderSide) - Required - The side of the order - **type** (OrderType) - Required - The type of the order - **quantity** (decimal) - Required - The quantity of the order #### Query Parameters - **price** (decimal) - Optional - The price of the order. Should be omitted for market orders - **clientOrderId** (string) - Optional - The clientOrderId the order should get - **source** (SourceType) - Optional - Source. defaults to SpotAPI - **stopPrice** (decimal) - Optional - Stop price - **stopOperator** (Operator) - Optional - Operator of the stop price - **ct** (CancellationToken) - Optional - Cancellation token ### Request Example APIDOC ### Response #### Success Response (200) - **Data** (long) - The ID of the placed order. ### Response Example APIDOC ``` -------------------------------- ### GetSymbolsAsync Source: https://github.com/jkorf/htx.net/wiki/ClientInfo/SpotApi/IHuobiClientSpotApiExchangeData Gets a list of all supported trading symbols on the Huobi exchange. ```APIDOC ## GetSymbolsAsync ### Description Gets a list of supported symbols. ### Method GET ### Endpoint /v1/common/symbols ### Response #### Success Response (200) - **data** (array) - List of HuobiSymbol objects ### Response Example ```json { "status": "ok", "data": [ { "base-currency": "usdt", "quote-currency": "btc", "price-precision": 2, "amount-precision": 8, "symbol-partition": "default", "symbol": "btcusdt" } ] } ``` ``` -------------------------------- ### Get Recent Trades Source: https://github.com/jkorf/htx.net/blob/master/HTX.Net.UnitTests/Endpoints/UsdtMarginSwap/ExchangeData/GetRecentTrades.txt Fetches the most recent trades for a specified symbol. ```APIDOC ## GET /linear-swap-ex/market/history/trade ### Description Retrieves a list of recent trades for a given symbol. ### Method GET ### Endpoint /linear-swap-ex/market/history/trade ### Query Parameters - **symbol** (string) - Required - The trading pair symbol (e.g., BTC-USDT). - **size** (integer) - Optional - The number of trades to retrieve (default is 50, max is 2000). - **fromId** (long) - Optional - Retrieve trades with IDs greater than this value. ### Response #### Success Response (200) - **ch** (string) - Channel name. - **data** (array) - Array of trade data objects. - **data** (array) - Array of individual trade details. - **amount** (decimal) - The amount of the trade. - **direction** (string) - The direction of the trade ('buy' or 'sell'). - **id** (long) - The trade ID. - **price** (decimal) - The price of the trade. - **ts** (long) - The timestamp of the trade. - **quantity** (decimal) - The quantity traded. - **trade_turnover** (decimal) - The turnover of the trade. - **id** (long) - The ID of the data batch. - **ts** (long) - The timestamp of the data batch. - **status** (string) - The status of the request ('ok' or 'error'). - **ts** (long) - The timestamp of the response. ### Response Example { "ch": "market.BTC-USDT.trade.detail", "data": [ { "data": [ { "amount": 2, "direction": "buy", "id": 1314767870000, "price": 13081.3, "ts": 1603695383124, "quantity": 0.002, "trade_turnover": 26.1626 } ], "id": 131476787, "ts": 1603695383124 } ], "status": "ok", "ts": 1603695388965 } ``` -------------------------------- ### Setup HTX REST Client for Public Data Source: https://github.com/jkorf/htx.net/blob/master/AGENTS.md Instantiate the HTXRestClient without credentials for accessing public market data. This client is suitable for read-only operations. ```csharp var publicClient = new HTXRestClient(); ``` -------------------------------- ### Add HTX with Configuration File Source: https://github.com/jkorf/htx.net/blob/master/docs/index.html Configure HTX options by referencing a configuration file. This is useful for managing sensitive API keys and other settings externally. ```csharp builder.Services.AddHTX(builder.Configuration.GetSection("HTX")); ``` -------------------------------- ### Get Last Trades Source: https://github.com/jkorf/htx.net/blob/master/HTX.Net.UnitTests/Endpoints/UsdtMarginSwap/ExchangeData/GetLastTrades.txt Fetches the most recent trades for a given market. ```APIDOC ## GET /linear-swap-ex/market/trade ### Description Retrieves the latest trade data for a specific contract, including details like price, quantity, timestamp, and trade direction. ### Method GET ### Endpoint /linear-swap-ex/market/trade ### Query Parameters - **contract_code** (string) - Required - The symbol of the contract (e.g., BTC-USDT). ### Response #### Success Response (200) - **ch** (string) - Channel name. - **status** (string) - Request status. - **tick** (object) - Contains trade data. - **data** (array) - Array of trade objects. - **amount** (string) - Trade amount. - **ts** (integer) - Timestamp of the trade. - **id** (integer) - Trade ID. - **price** (string) - Trade price. - **direction** (string) - Trade direction (e.g., buy, sell). - **quantity** (float) - Trade quantity. - **contract_code** (string) - Contract symbol. - **business_type** (string) - Business type (e.g., swap). - **trade_turnover** (float) - Trade turnover. - **id** (integer) - Tick ID. - **ts** (integer) - Tick timestamp. - **ts** (integer) - Response timestamp. ### Response Example ```json { "ch": "market.*.trade.detail", "status": "ok", "tick": { "data": [ { "amount": "6", "ts": 1603695230083, "id": 1314755250000, "price": "13083", "direction": "buy", "quantity": 0.006, "contract_code": "BTC-USDT", "business_type": "swap", "trade_turnover": 78.498 } ], "id": 1603695235127, "ts": 1603695235127 }, "ts": 1603695235127 } ``` ``` -------------------------------- ### Map Common WebSocket Tasks to HTX.NET Methods Source: https://github.com/jkorf/htx.net/blob/master/llms-full.txt Provides a quick reference for common WebSocket operations, mapping user intents to specific client subscription method calls. ```text Subscribe spot ticker -> socketClient.SpotApi.SubscribeToTickerUpdatesAsync(symbol, handler) Subscribe all spot tickers -> socketClient.SpotApi.SubscribeToTickerUpdatesAsync(handler) Subscribe spot klines -> socketClient.SpotApi.SubscribeToKlineUpdatesAsync(symbol, interval, handler) Subscribe spot order book -> socketClient.SpotApi.SubscribeToPartialOrderBookUpdates1SecondAsync(...) Subscribe spot trades -> socketClient.SpotApi.SubscribeToTradeUpdatesAsync(symbol, handler) Subscribe spot account updates -> socketClient.SpotApi.SubscribeToAccountUpdatesAsync(handler) Subscribe spot order updates -> socketClient.SpotApi.SubscribeToOrderUpdatesAsync(...) Subscribe futures ticker -> socketClient.UsdtFuturesApi.SubscribeToTickerUpdatesAsync(contractCode, handler) Subscribe futures klines -> socketClient.UsdtFuturesApi.SubscribeToKlineUpdatesAsync(contractCode, interval, handler) Subscribe futures order updates -> socketClient.UsdtFuturesApi.SubscribeToOrderUpdatesAsync(MarginMode.Cross, handler) Subscribe futures balances -> socketClient.UsdtFuturesApi.SubscribeToCrossMarginBalanceUpdatesAsync(handler) Subscribe futures positions -> socketClient.UsdtFuturesApi.SubscribeToCrossMarginPositionUpdatesAsync(handler) ```