### Spot Quickstart Example Source: https://github.com/jkorf/binance.net/blob/master/llms.txt Demonstrates basic client setup, fetching ticker data, checking account balance, placing a limit order, and retrieving order status. ```csharp using Binance.Net; using Binance.Net.Enums; using System; using System.Threading.Tasks; public class SpotQuickstart { public static async Task RunAsync() { // Initialize the client. API keys are optional for public endpoints. using var client = new BinanceClient(); // Get ticker for BTC/USDT var tickerResult = await client.SpotApi.ExchangeData.GetTickerAsync("BTCUSDT"); if (tickerResult.Success) { Console.WriteLine($"BTCUSDT Price: {tickerResult.Data.LastPrice}"); } else { Console.WriteLine($"Error getting ticker: {tickerResult.Error.Message}"); } // Get account balance (requires API keys) // var balanceResult = await client.SpotApi.Account.GetAccountInfoAsync(); // if (balanceResult.Success) // { // Console.WriteLine($"Account Free BTC: {balanceResult.Data.Balances.First(b => b.Asset == "BTC").Free}"); // } // Place a limit order (requires API keys) // var orderResult = await client.SpotApi.Trading.PlaceOrderAsync( // "BTCUSDT", // OrderSide.Buy, // OrderType.Limit, // TimeInForce.GoodTillCanceled, // 10000m, // Quantity // 10000m); // Price // if (orderResult.Success) // { // Console.WriteLine($"Placed order with ID: {orderResult.Data.OrderId}"); // } // Get order status (requires API keys) // if (orderResult.Success) // { // var orderStatusResult = await client.SpotApi.Trading.GetOrderAsync("BTCUSDT", orderResult.Data.OrderId); // if (orderStatusResult.Success) // { // Console.WriteLine($"Order Status: {orderStatusResult.Data.Status}"); // } // } } } ``` -------------------------------- ### Setup Console Project and Add Binance.Net Package Source: https://github.com/jkorf/binance.net/blob/master/Examples/ai-friendly/README.md Instructions for setting up a new .NET console project and adding the necessary Binance.Net NuGet package. This is the initial step before incorporating any of the provided C# examples. ```bash dotnet new console -n MyBinanceApp cd MyBinanceApp dotnet add package Binance.Net ``` -------------------------------- ### Start User Stream for Spot Account Source: https://github.com/jkorf/binance.net/wiki/Usage Starts a user data stream to receive real-time updates on account activity. ```APIDOC ## Start User Stream ### Description Starts a user data stream to receive real-time notifications for account updates, orders, and trades. ### Method POST ### Endpoint /api/v3/userDataStream ### Response #### Success Response (200) - **listenKey** (string) - The key required to subscribe to user data streams. ### Request Example ```csharp var listenKey = await binanceClient.SpotApi.Account.StartUserStreamAsync(); if (!listenKey.Success) { // Handler failure return; } ``` ``` -------------------------------- ### Get System Status Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiExchangeData Gets the status of the Binance platform. Supports cancellation via a token. ```C# Task> GetSystemStatusAsync([Optional] CancellationToken ct); ``` -------------------------------- ### Get Prevented Trades Request Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/Spot/Trading/GetPreventedTrades.txt This is an example of a request payload to get prevented trades. Ensure your API key and timestamp are correctly set. ```json { "id": "|1|", "method": "myPreventedMatches", "params": { "apiKey": "123", "signature": "-", "timestamp": 1660801839480 } } ``` -------------------------------- ### Client Creation Source: https://github.com/jkorf/binance.net/wiki/Usage Demonstrates how to create instances of BinanceClient and BinanceSocketClient, with options for configuration. ```APIDOC ## Creating client There are 2 clients available to interact with the Binance API, the `BinanceClient` and `BinanceSocketClient`. *Create a new rest client* ```C# var binanceClient = new BinanceClient(new BinanceClientOptions() { // Set options here for this client }); ``` *Create a new socket client* ```C# var binanceSocketClient = new BinanceSocketClient(new BinanceSocketClientOptions() { // Set options here for this client }); ``` Different options are available to set on the clients, see this example ```C# var binanceClient = new BinanceClient(new BinanceClientOptions { ApiCredentials = new ApiCredentials("API-KEY", "API-SECRET"), SpotApiOptions = new BinanceApiClientOptions { BaseAddress = "ADDRESS", RateLimitingBehaviour = RateLimitingBehaviour.Fail }, UsdFuturesApiOptions = new BinanceApiClientOptions { ApiCredentials = new ApiCredentials("OTHER-API-KEY-FOR-FUTURES", "OTHER-API-SECRET-FOR-FUTURES") } }); ``` Alternatively, options can be provided before creating clients by using `SetDefaultOptions`: ```C# BinanceClient.SetDefaultOptions(new BinanceClientOptions{ // Set options here for all new clients }); var binanceClient = new BinanceClient(); ``` ``` -------------------------------- ### Get Book Price Request Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/UsdFutures/ExchangeData/GetBookPrice.txt This is an example of a JSON request payload to get the book price for a symbol. It includes the method, parameters, and authentication details. ```json { "id": "|1|", "method": "ticker.book", "params": { "apiKey": "123", "signature": "-", "timestamp": 1660801839480 } } ``` -------------------------------- ### Get Coin Futures Positions Request Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/CoinFutures/Trading/GetPositions.txt This is an example of a request payload to get coin futures positions. Ensure you include your API key, a valid signature, and the current timestamp. ```json { "id": "|1|", "method": "account.position", "params": { "apiKey": "123", "signature": "-", "timestamp": 1660801839480 } } ``` -------------------------------- ### REST Client Setup Source: https://github.com/jkorf/binance.net/blob/master/AGENTS.md Demonstrates how to initialize the BinanceRestClient for trading with API credentials or for public market data without credentials. ```APIDOC ## REST Client Setup Always create the client via `BinanceRestClient`. For trading, configure credentials. ```csharp using Binance.Net.Clients; using Binance.Net; using Binance.Net.Objects; var restClient = new BinanceRestClient(options => { options.ApiCredentials = new BinanceCredentials("API_KEY", "API_SECRET"); }); ``` For read-only / public market data, credentials are not required: ```csharp var publicClient = new BinanceRestClient(); ``` ``` -------------------------------- ### AI-Friendly Example File List Source: https://github.com/jkorf/binance.net/blob/master/llms-full.txt A list of AI-friendly example C# files for Binance.Net, covering various functionalities like spot trading, futures, websockets, and error handling. ```text Examples/ai-friendly/01-spot-quickstart.cs Client setup, public ticker, authenticated account balance, limit spot order, order status, cancellation. Examples/ai-friendly/02-futures.cs USD-M futures leverage, market order, position lookup, reduce-only close. Examples/ai-friendly/03-websocket.cs Public ticker stream, kline stream, authenticated user data stream, success checks, teardown. Examples/ai-friendly/04-multi-exchange.cs CryptoExchange.Net.SharedApis REST and socket patterns. Examples/ai-friendly/05-error-handling.cs WebCallResult pattern, transient retry, Binance error examples, exchange filter handling. ``` -------------------------------- ### Get Coin Futures Account Info Request Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/CoinFutures/Account/GetAccountInfo.txt This is an example of a request payload to get account information for Coin Futures. It includes the method and parameters required for authentication and the specific endpoint. ```json { "id": "|1|", "method": "account.status", "params": { "apiKey": "123", "signature": "-", "timestamp": 1660801839480 } } ``` -------------------------------- ### Get Top Long/Short Account Ratio Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/CoinFuturesApi/IBinanceClientCoinFuturesApiExchangeData Gets the Top Trader Long/Short Ratio for accounts for a specified symbol and period. Supports optional limit, start time, end time, and cancellation token. ```C# Task>> GetTopLongShortAccountRatioAsync(string symbol, PeriodInterval period, int? limit, DateTime? startTime, DateTime? endTime, [Optional] CancellationToken ct); ``` -------------------------------- ### Dependency Injection Setup Source: https://github.com/jkorf/binance.net/blob/master/llms-full.txt Configure Binance.Net services for dependency injection, including API credentials. ```csharp services.AddBinance(options => { options.Rest.ApiCredentials = new BinanceCredentials("API_KEY", "API_SECRET"); options.Socket.ApiCredentials = new BinanceCredentials("API_KEY", "API_SECRET"); }); ``` -------------------------------- ### Socket Client Setup with Credentials Source: https://github.com/jkorf/binance.net/blob/master/llms-full.txt Instantiate a BinanceSocketClient and provide API credentials for authenticated WebSocket connections. ```csharp var socketClient = new BinanceSocketClient(options => { options.ApiCredentials = new BinanceCredentials("API_KEY", "API_SECRET"); }); ``` -------------------------------- ### Get Taker Buy/Sell Volume Ratio Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/CoinFuturesApi/IBinanceClientCoinFuturesApiExchangeData Gets the Taker Buy/Sell Volume Ratio for a specified pair and contract type over a given period. Supports optional limit, start time, end time, and cancellation token. ```C# Task>> GetTakerBuySellVolumeRatioAsync(string pair, ContractType contractType, PeriodInterval period, [Optional] int? limit, [Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] CancellationToken ct); ``` -------------------------------- ### Get Prevented Trades Response Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/Spot/Trading/GetPreventedTrades.txt This is an example of a successful response when retrieving prevented trades. It includes details of the prevented matches. ```json { "id": "|1|", "status": 200, "result": [ { "symbol": "BTCUSDT", "preventedMatchId": 1, "takerOrderId": 5, "makerSymbol": "BTCUSDT", "makerOrderId": 3, "tradeGroupId": 1, "selfTradePreventionMode": "EXPIRE_MAKER", "price": "1.100000", "makerPreventedQuantity": "1.300000", "transactTime": 1669101687094 } ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000, "count": 20 } ] } ``` -------------------------------- ### Initialize Binance REST Client with Credentials Source: https://github.com/jkorf/binance.net/blob/master/AGENTS.md Create an instance of `BinanceRestClient` and configure it with your API key and secret for authenticated requests. This client is used for trading and account management. ```csharp using Binance.Net.Clients; using Binance.Net; using Binance.Net.Objects; var restClient = new BinanceRestClient(options => { options.ApiCredentials = new BinanceCredentials("API_KEY", "API_SECRET"); }); ``` -------------------------------- ### Get Trade History Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/CoinFuturesApi/IBinanceClientCoinFuturesApiExchangeData Fetches historical trades for a specified symbol. Allows filtering by limit and a starting trade ID. ```C# Task>> GetTradeHistoryAsync(string symbol, [Optional] int? limit, [Optional] long? fromId, [Optional] CancellationToken ct); ``` -------------------------------- ### Configure Binance Client Options (v8) Source: https://github.com/jkorf/binance.net/wiki/MigrationGuide Example of configuring BinanceClient options in version 8.x.x, demonstrating the new structure for API-specific options like Spot and USD Futures. ```csharp var binanceClient = new BinanceClient(new BinanceClientOptions { ApiCredentials = new ApiCredentials("API-KEY", "API-SECRET"), SpotApiOptions = new BinanceApiClientOptions { BaseAddress = BinanceApiAddresses.Default.RestClientAddress, AutoTimestamp = false }, UsdFuturesApiOptions = new BinanceApiClientOptions { TradeRulesBehaviour = TradeRulesBehaviour.ThrowError, BaseAddress = BinanceApiAddresses.Default.UsdFuturesRestClientAddress, AutoTimestamp = true } }); ``` -------------------------------- ### Create BinanceClient Instance Source: https://github.com/jkorf/binance.net/wiki/Usage Instantiate a new BinanceClient with default options. Further configuration can be applied via BinanceClientOptions. ```C# var binanceClient = new BinanceClient(new BinanceClientOptions() { // Set options here for this client }); ``` -------------------------------- ### Get Auto-Invest Index Info Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Endpoints/General/AutoInvest/GetIndexInfo.txt This snippet shows how to retrieve the details of an Auto-Invest index. Ensure you have the necessary authentication and client setup. ```csharp var result = await BinanceClient.SpotApi.AutoInvest.GetIndexInfoAsync(1); // result.Data.Should().NotBeNull(); // result.Data.IndexId.Should().Be(1); // result.Data.IndexName.Should().Be("BINANCE TOP 10 EW "); // result.Data.Status.Should().Be(AutoInvestIndexStatus.Running); // result.Data.AssetAllocation.Should().HaveCount(2); // result.Data.AssetAllocation[0].TargetAsset.Should().Be("ADA"); // result.Data.AssetAllocation[0].Allocation.Should().Be("10"); // result.Data.AssetAllocation[1].TargetAsset.Should().Be("BTC"); // result.Data.AssetAllocation[1].Allocation.Should().Be("10"); ``` -------------------------------- ### Futures Trading Example Source: https://github.com/jkorf/binance.net/blob/master/llms.txt Illustrates how to perform USD-M futures trading, including setting leverage, placing market orders, retrieving positions, and closing positions. ```csharp using Binance.Net; using Binance.Net.Enums; using System; using System.Threading.Tasks; public class FuturesTrading { public static async Task RunAsync() { // Initialize the client with API keys for trading using var client = new BinanceClient(new ClientOptions { ApiCredentials = new ApiCredentials("YOUR_API_KEY", "YOUR_API_SECRET") }); // Set leverage for a symbol var leverageResult = await client.UsdFuturesApi.Trading.ChangeLeverageAsync("BTCUSDT", 10); if (leverageResult.Success) { Console.WriteLine("Leverage set successfully."); } else { Console.WriteLine($"Error setting leverage: {leverageResult.Error.Message}"); } // Place a market order var orderResult = await client.UsdFuturesApi.Trading.PlaceOrderAsync( "BTCUSDT", OrderSide.Buy, OrderType.Market, 100m); // Quantity if (orderResult.Success) { Console.WriteLine($"Market order placed. Position ID: {orderResult.Data.PositionId}"); } else { Console.WriteLine($"Error placing order: {orderResult.Error.Message}"); } // Get current positions var positionsResult = await client.UsdFuturesApi.Account.GetPositionsAsync("BTCUSDT"); if (positionsResult.Success) { var position = positionsResult.Data.First(p => p.Symbol == "BTCUSDT"); Console.WriteLine($"Current Position: {position.Side} {position.Quantity} contracts."); } // Close the position var closeResult = await client.UsdFuturesApi.Trading.PlaceOrderAsync( "BTCUSDT", OrderSide.Sell, // Opposite side to close OrderType.Market, orderResult.Data.Quantity); // Quantity to close if (closeResult.Success) { Console.WriteLine("Position closed successfully."); } else { Console.WriteLine($"Error closing position: {closeResult.Error.Message}"); } } } ``` -------------------------------- ### Get Deposit History Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiAccount Retrieves the deposit history. Can be filtered by asset, status, start time, end time, offset, and limit. ```C# Task>> GetDepositHistoryAsync([Optional] string? asset, [Optional] DepositStatus? status, [Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] int? offset, [Optional] int? limit, [Optional] int? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Initialize Binance REST Client Source: https://github.com/jkorf/binance.net/blob/master/docs/ai-api-map.md Instantiate the Binance REST client for making API calls. ```csharp new BinanceRestClient() ``` -------------------------------- ### Get Recent Trades Response Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/Spot/ExchangeData/GetRecentTrades.txt This is an example of a successful response when retrieving recent trades. It includes trade details and rate limit information. ```json { "id": "|1|", "status": 200, "result": [ { "id": 194686783, "price": "0.01361000", "qty": "0.01400000", "quoteQty": "0.00019054", "time": 1660009530807, "isBuyerMaker": true, "isBestMatch": true } ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000, "count": 2 } ] } ``` -------------------------------- ### USD Futures Account Balance Request Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/UsdFutures/Account/GetBalances.txt This is an example of a request to get the USD Futures account balance. It includes the method, parameters, and authentication details. ```json { "id": "|1|", "method": "v2/account.balance", "params": { "apiKey": "123", "signature": "-", "timestamp": 1660801839480 } } ``` -------------------------------- ### Install Binance.Net Package Source: https://github.com/jkorf/binance.net/blob/master/AGENTS.md Use the dotnet CLI to add the Binance.Net package to your project. This package supports multiple .NET target frameworks and Native AOT. ```bash dotnet add package Binance.Net ``` -------------------------------- ### Get Dust Log Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiAccount Retrieves the history of dust conversions. Optional parameters include start and end times, receive window, and cancellation token. ```C# Task> GetDustLogAsync([Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] int? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Place Spot Market Order with Quote Quantity Source: https://github.com/jkorf/binance.net/blob/master/llms-full.txt This example shows how to place a market order on the spot market, specifying the amount in quote currency (e.g., USDT). ```csharp var order = await client.SpotApi.Trading.PlaceOrderAsync( symbol: "BTCUSDT", side: OrderSide.Buy, type: SpotOrderType.Market, quoteQuantity: 100m); ``` -------------------------------- ### Configure Binance Client Options (v7) Source: https://github.com/jkorf/binance.net/wiki/MigrationGuide Example of configuring BinanceClient options in version 7.x.x, including log level, API credentials, base addresses, auto timestamping, and trade rules behavior. ```csharp var binanceClient = new BinanceClient(new BinanceClientOptions { LogLevel = LogLevel.Debug, ApiCredentials = new ApiCredentials("GENERAL-KEY", "GENERAL-SECRET"), BaseAddress = BinanceApiAddresses.Default.RestClientAddress, BaseAddressUsdtFutures = BinanceApiAddresses.Default.UsdtFuturesRestClientAddress, AutoTimestamp = true, TradeRulesBehaviour = TradeRulesBehaviour.ThrowError }); ``` -------------------------------- ### Get Locked Redemption Records Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Endpoints/General/SimpleEarn/GetLockedRedemptionRecords.txt Fetches redemption records for locked Simple Earn products. Supports filtering by asset, start time, and end time. ```APIDOC ## GET /sapi/v1/simple-earn/locked/history/redemptionRecord ### Description Retrieves a list of redemption records for locked Simple Earn products. ### Method GET ### Endpoint /sapi/v1/simple-earn/locked/history/redemptionRecord ### Query Parameters - **startTime** (long) - Optional - The start time to query in milliseconds. - **endTime** (long) - Optional - The end time to query in milliseconds. - **asset** (string) - Optional - The asset to query. - **current** (long) - Optional - Current page number. - **size** (long) - Optional - Default 10, max 100. ### Response #### Success Response (200) - **rows** (array) - List of redemption records. - **positionId** (long) - The ID of the position. - **redeemId** (long) - The ID of the redemption. - **time** (long) - The time of the redemption in milliseconds. - **asset** (string) - The asset redeemed. - **lockPeriod** (string) - The lock period. - **amount** (string) - The amount redeemed. - **originalAmount** (string) - The original amount. - **type** (string) - The type of redemption (e.g., MATURE). - **deliverDate** (string) - The delivery date in milliseconds. - **lossAmount** (string) - The loss amount. - **isComplete** (boolean) - Whether the redemption is complete. - **rewardAsset** (string) - The reward asset. - **rewardAmt** (string) - The reward amount. - **extraRewardAsset** (string) - The extra reward asset. - **estExtraRewardAmt** (string) - The estimated extra reward amount. - **status** (string) - The status of the redemption (e.g., PAID). - **total** (long) - The total number of records. ``` -------------------------------- ### Client Roots Source: https://github.com/jkorf/binance.net/blob/master/docs/ai-api-map.md These are the fundamental client initializations and configurations for using the Binance.Net library. ```APIDOC ## Client Roots ### REST Calls ```csharp var client = new BinanceRestClient(); ``` ### WebSocket Streams and Socket API Requests ```csharp var client = new BinanceSocketClient(); ``` ### API Key Authentication ```csharp var options = new BinanceClientOptions { ApiCredentials = new BinanceCredentials("YOUR_API_KEY", "YOUR_API_SECRET") }; var client = new BinanceRestClient(options); ``` ### Environment Configuration - **Live Environment**: `BinanceEnvironment.Live` - **Testnet Environment**: `BinanceEnvironment.Testnet` - **Binance.US Environment**: `BinanceEnvironment.Us` ### Dependency Injection ```csharp // In your Startup.cs or equivalent services.AddBinance(options => { options.ApiCredentials = new BinanceCredentials("YOUR_API_KEY", "YOUR_API_SECRET"); options.Environment = BinanceEnvironment.Testnet; }); ``` ``` -------------------------------- ### Get Book Price Response Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/UsdFutures/ExchangeData/GetBookPrice.txt This is an example of a JSON response when requesting the book price. It contains the symbol, bid/ask prices and quantities, and the last update ID. ```json { "id": "|1|", "status": 200, "result": { "lastUpdateId": 1027024, "symbol": "BTCUSDT", "bidPrice": "4.00000000", "bidQty": "431.00000000", "askPrice": "4.00000200", "askQty": "9.00000000", "time": 1589437530011 }, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "count": 2 } ] } ``` -------------------------------- ### Place Order Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiTrading Place a new order on the Binance Spot market. This is a general-purpose method for various order types. ```C# Task> PlaceOrderAsync(string symbol, OrderSide side, OrderType type, [Optional] decimal? quantity, [Optional] decimal? quoteQuantity, [Optional] string? newClientOrderId, [Optional] decimal? price, [Optional] TimeInForce? timeInForce, [Optional] decimal? stopPrice, [Optional] decimal? icebergQty, [Optional] OrderResponseType? orderResponseType, [Optional] int? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Get Crypto Loans Income History Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/GeneralApi/IBinanceClientGeneralApiLending Retrieves the income history for crypto loans. Supports filtering by asset, type, start and end times, and limit. ```C# Task>> GetCryptoLoansIncomeHistoryAsync(string asset, [Optional] LoanIncomeType? type, [Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] int? limit, [Optional] long? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Configure Binance with Dependency Injection Source: https://github.com/jkorf/binance.net/blob/master/docs/index.html Configure Binance.Net clients using .NET dependency injection. Options can be loaded from a configuration file or set directly in code. ```csharp builder.Services.AddBinance(builder.Configuration.GetSection("Binance")); ``` ```csharp builder.Services.AddBinance(options => { // Configure options in code options.ApiCredentials = new ApiCredentials("APIKEY", "APISECRET"); }); ``` -------------------------------- ### Get Coin Futures Positions Response Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/CoinFutures/Trading/GetPositions.txt This is an example of a successful response when retrieving coin futures positions. It includes details for each open position and rate limit information. ```json { "id": "|1|", "status": 200, "result": [ { "symbol": "BTCUSD_PERP", "positionAmt": "0", "entryPrice": "0.00000000", "markPrice": "62297.60417296", "unRealizedProfit": "0.00000000", "liquidationPrice": "0", "leverage": "7", "maxQty": "100", "marginType": "cross", "isolatedMargin": "0.00000000", "isAutoAddMargin": "false", "positionSide": "BOTH", "notionalValue": "0", "isolatedWallet": "0", "updateTime": 1726731195634, "breakEvenPrice": "0.00000000" } ], "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "count": 10 } ] } ``` -------------------------------- ### Start User Stream Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/CoinFuturesApi/IBinanceClientCoinFuturesApiAccount Initiates a user data stream. The returned listen key is used to subscribe to the stream via a socket client. This stream needs to be kept alive by calling it every 30 minutes. ```C# Task> StartUserStreamAsync([Optional] CancellationToken ct); ``` -------------------------------- ### Get Aggregated Trade History Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Endpoints/CoinFutures/ExchangeData/GetAggregatedTradeHistory.txt Retrieves aggregated trades for a symbol. Specify start and end times for a specific period. Ensure the symbol is valid and the time range is appropriate. ```json [ { "a": 416690, "p": "9642.4", "q": "3", "f": 595259, "l": 595259, "T": 1591250548649, "m": false } ] ``` -------------------------------- ### Create BinanceSocketClient Instance Source: https://github.com/jkorf/binance.net/wiki/Usage Instantiate a new BinanceSocketClient for real-time data streams. Options can be set using BinanceSocketClientOptions. ```C# var binanceSocketClient = new BinanceSocketClient(new BinanceSocketClientOptions() { // Set options here for this client }); ``` -------------------------------- ### Get Order Status Response Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/Spot/Trading/GetOrder.txt This is an example of a successful response when retrieving order status. It contains detailed information about the order, including its symbol, quantities, price, status, and timestamps. ```json { "id": "|1|", "status": 200, "result": { "symbol": "BTCUSDT", "orderId": 12569099453, "orderListId": -1, "clientOrderId": "4d96324ff9d44481926157", "price": "23416.10000000", "origQty": "0.00847000", "executedQty": "0.00847000", "cummulativeQuoteQty": "198.33521500", "status": "FILLED", "timeInForce": "GTC", "type": "LIMIT", "side": "SELL", "stopPrice": "0.00000000", "trailingDelta": 10, "trailingTime": -1, "icebergQty": "0.00000000", "time": 1660801715639, "updateTime": 1660801717945, "isWorking": true, "workingTime": 1660801715639, "origQuoteOrderQty": "0.00000000", "strategyId": 37463720, "strategyType": 1000000, "selfTradePreventionMode": "NONE", "preventedMatchId": 0, "preventedQuantity": "1.200000" }, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 6000, "count": 4 } ] } ``` -------------------------------- ### Get Leveraged Tokens Historical Klines Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiExchangeData Fetches historical candlestick data for leveraged tokens. Requires symbol and interval, with optional start time, end time, and limit. ```C# Task>> GetLeveragedTokensHistoricalKlinesAsync(string symbol, KlineInterval interval, [Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] int? limit, [Optional] int? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Initialize Binance WebSocket Client Source: https://github.com/jkorf/binance.net/blob/master/docs/ai-api-map.md Instantiate the Binance WebSocket client for handling real-time streams and socket API requests. ```csharp new BinanceSocketClient() ``` -------------------------------- ### Get Futures Transfer History Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/GeneralApi/IBinanceClientGeneralApiFutures Retrieves the history of transfers between spot and futures accounts. Requires asset and start time, with optional end time, page, limit, and receive window. ```C# Task>> GetFuturesTransferHistoryAsync(string asset, DateTime startTime, [Optional] DateTime? endTime, [Optional] int? page, [Optional] int? limit, [Optional] long? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### WebSocket Streams Example Source: https://github.com/jkorf/binance.net/blob/master/llms.txt Shows how to subscribe to WebSocket streams for real-time data, including ticker updates, kline data, and user data streams. Includes proper teardown. ```csharp using Binance.Net; using Binance.Net.Enums; using System; using System.Threading.Tasks; public class WebSocketStreams { public static async Task RunAsync() { // Initialize the client using var client = new BinanceClient(); // Subscribe to ticker updates for BTCUSDT var tickerSubscriptionResult = await client.SpotStreams.SubscribeToSymbolTickerUpdatesAsync("BTCUSDT", Console.WriteLine); if (!tickerSubscriptionResult.Success) { Console.WriteLine($"Error subscribing to ticker: {tickerSubscriptionResult.Error.Message}"); } // Subscribe to kline updates for BTCUSDT (1 minute intervals) var klineSubscriptionResult = await client.SpotStreams.SubscribeToKlineUpdatesAsync("BTCUSDT", KlineInterval.OneMinute, Console.WriteLine); if (!klineSubscriptionResult.Success) { Console.WriteLine($"Error subscribing to klines: {klineSubscriptionResult.Error.Message}"); } // Subscribe to user data stream (requires API keys and a listen key) // var listenKeyResult = await client.SpotApi.User.StartUserStreamAsync(); // if (listenKeyResult.Success) // { // var userDataSubscriptionResult = await client.SpotStreams.SubscribeToUserDataUpdatesAsync(listenKeyResult.Data.ListenKey, Console.WriteLine); // if (!userDataSubscriptionResult.Success) // { // Console.WriteLine($"Error subscribing to user data: {userDataSubscriptionResult.Error.Message}"); // } // // Keep the stream alive by periodically extending the listen key // // await client.SpotApi.User.KeepAliveUserStreamAsync(listenKeyResult.Data.ListenKey); // } Console.WriteLine("Subscribed to streams. Press Enter to stop."); Console.ReadLine(); // Unsubscribe from streams if (tickerSubscriptionResult.Success) { await client.UnsubscribeAsync(tickerSubscriptionResult.Data); Console.WriteLine("Unsubscribed from ticker stream."); } if (klineSubscriptionResult.Success) { await client.UnsubscribeAsync(klineSubscriptionResult.Data); Console.WriteLine("Unsubscribed from kline stream."); } // if (userDataSubscriptionResult.Success) // { // await client.UnsubscribeAsync(userDataSubscriptionResult.Data); // Console.WriteLine("Unsubscribed from user data stream."); // // Also stop the user stream on the server // // await client.SpotApi.User.StopUserStreamAsync(listenKeyResult.Data.ListenKey); // } } } ``` -------------------------------- ### Private Account/Trading Client Setup Source: https://github.com/jkorf/binance.net/blob/master/llms-full.txt Configure BinanceRestClient with API credentials for accessing private endpoints. ```csharp var client = new BinanceRestClient(options => { options.ApiCredentials = new BinanceCredentials("API_KEY", "API_SECRET"); }); ``` -------------------------------- ### Get Daily Spot Account Snapshot Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiAccount Retrieves a daily snapshot of spot account balances. Optional parameters include start time, end time, and limit for the number of days. ```C# Task>> GetDailySpotAccountSnapshotAsync([Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] int? limit, [Optional] long? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Get Daily Margin Account Snapshot Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiAccount Retrieves a daily snapshot of margin account data. Optional parameters include start time, end time, and limit for the number of days. ```C# Task>> GetDailyMarginAccountSnapshotAsync([Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] int? limit, [Optional] long? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Initialize BinanceRestClient Correctly Source: https://github.com/jkorf/binance.net/blob/master/llms-full.txt Use BinanceRestClient for REST API interactions instead of the generic BinanceClient. ```csharp var client = new BinanceRestClient(); ``` -------------------------------- ### Placing a Futures Order Source: https://github.com/jkorf/binance.net/blob/master/AGENTS.md Shows how to place a market order for USD-M futures, including an example of setting leverage before placing the order. Mentions `PositionSide` for hedge mode. ```APIDOC ## Placing a Futures Order ```csharp using Binance.Net.Enums; // Set leverage first if needed await restClient.UsdFuturesApi.Account.ChangeInitialLeverageAsync("ETHUSDT", 10); var order = await restClient.UsdFuturesApi.Trading.PlaceOrderAsync( symbol: "ETHUSDT", side: OrderSide.Buy, type: FuturesOrderType.Market, quantity: 0.1m); // In Hedge mode add positionSide: PositionSide.Long / PositionSide.Short. ``` ``` -------------------------------- ### Get Daily Future Account Snapshot Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiAccount Retrieves a daily snapshot of futures account data. Optional parameters include start time, end time, and limit for the number of days. ```C# Task>> GetDailyFutureAccountSnapshotAsync([Optional] DateTime? startTime, [Optional] DateTime? endTime, [Optional] int? limit, [Optional] long? receiveWindow, [Optional] CancellationToken ct); ``` -------------------------------- ### Get Top Long Short Position Ratio Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/CoinFuturesApi/IBinanceClientCoinFuturesApiExchangeData Retrieves the top trader long/short ratio for a given symbol and period. Supports filtering by limit, start time, and end time. ```C# Task>> GetTopLongShortPositionRatioAsync(string symbol, PeriodInterval period, int? limit, DateTime? startTime, DateTime? endTime, [Optional] CancellationToken ct); ``` -------------------------------- ### Get Products Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/SpotApi/IBinanceClientSpotApiExchangeData Retrieves general data for all products available on Binance. Note: This is not an official endpoint and may be subject to change. ```C# Task>> GetProductsAsync([Optional] CancellationToken ct); ``` -------------------------------- ### Place a Spot Limit Order Source: https://github.com/jkorf/binance.net/blob/master/AGENTS.md Use the `PlaceOrderAsync` method on the `SpotApi.Trading` client to place a limit order. It is recommended to let the library auto-generate the `clientOrderId` for better tracking. ```csharp using Binance.Net.Enums; var order = await restClient.SpotApi.Trading.PlaceOrderAsync( symbol: "BTCUSDT", side: OrderSide.Buy, type: SpotOrderType.Limit, quantity: 0.001m, price: 50000m, timeInForce: TimeInForce.GoodTillCanceled); if (!order.Success) { /* handle */ return; } var orderId = order.Data.Id; ``` -------------------------------- ### Get USD Futures Ticker Price Response Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/UsdFutures/ExchangeData/GetPrice.txt This is an example of a successful response when requesting the ticker price for a symbol in Binance USD Futures. It includes the symbol, current price, and the timestamp of the data. ```json { "id": "|1|", "status": 200, "result": { "symbol": "BTCUSDT", "price": "6000.01", "time": 1589437530011 }, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "count": 2 } ] } ``` -------------------------------- ### Get Coin Futures Account Info Response Source: https://github.com/jkorf/binance.net/blob/master/Binance.Net.UnitTests/Socket/CoinFutures/Account/GetAccountInfo.txt This is an example of a successful response when retrieving account information for Coin Futures. It contains details about the account's trading status, assets, and open positions. ```json { "id": "|1|", "status": 200, "result": { "feeTier": 0, "canTrade": true, "canDeposit": true, "canWithdraw": true, "updateTime": 0, "assets": [ { "asset": "WLD", "walletBalance": "0.00000000", "unrealizedProfit": "0.00000000", "marginBalance": "0.00000000", "maintMargin": "0.00000000", "initialMargin": "0.00000000", "positionInitialMargin": "0.00000000", "openOrderInitialMargin": "0.00000000", "maxWithdrawAmount": "0.00000000", "crossWalletBalance": "0.00000000", "crossUnPnl": "0.00000000", "availableBalance": "0.00000000", "updateTime": 0 } ], "positions": [ { "symbol": "ETHUSD_220930", "initialMargin": "0", "maintMargin": "0", "unrealizedProfit": "0.00000000", "positionInitialMargin": "0", "openOrderInitialMargin": "0", "leverage": "7", "isolated": false, "positionSide": "BOTH", "entryPrice": "0.00000000", "maxQty": "1000", "notionalValue": "0", "isolatedWallet": "0", "updateTime": 0, "positionAmt": "0", "breakEvenPrice": "0.00000000" } ] }, "rateLimits": [ { "rateLimitType": "REQUEST_WEIGHT", "interval": "MINUTE", "intervalNum": 1, "limit": 2400, "count": 10 } ] } ``` -------------------------------- ### Spot API - Placing Orders Source: https://github.com/jkorf/binance.net/wiki/Usage Provides examples for placing various types of orders on the Spot API, including limit, market, and stop-limit orders. ```APIDOC #### Placing order ````C# // Placing a buy limit order for 0.001 BTC at a price of 50000USDT each var orderData = await binanceClient.SpotApi.Trading.PlaceOrderAsync( "BTCUSDT", OrderSide.Buy, OrderType.Limit, 0.001m, 50000, timeInForce: TimeInForce.GoodTillCanceled); // Placing a market buy order for 50USDT var orderData = await binanceClient.SpotApi.Trading.PlaceOrderAsync( "BTCUSDT", OrderSide.Buy, OrderType.Market, quoteQuantity: 50); // 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 binanceClient.SpotApi.Trading.PlaceOrderAsync( "BTCUSDT", OrderSide.Buy, OrderType.StopLossLimit, 0.001m, 39000, timeInForce: TimeInForce.GoodTillCancel, stopPrice: 40000); ```` ``` -------------------------------- ### Environment Configuration Source: https://github.com/jkorf/binance.net/blob/master/llms-full.txt Set the Binance environment (Live, Testnet, or US) when creating a BinanceRestClient. ```csharp var live = new BinanceRestClient(options => options.Environment = BinanceEnvironment.Live); var testnet = new BinanceRestClient(options => options.Environment = BinanceEnvironment.Testnet); var us = new BinanceRestClient(options => options.Environment = BinanceEnvironment.Us); ``` -------------------------------- ### Get Redemption Records Async Source: https://github.com/jkorf/binance.net/wiki/ClientInfo/GeneralApi/IBinanceClientGeneralApiLending Retrieves redemption records for a specified lending type. Supports filtering by asset, start and end times, and pagination. Optional parameters include receive window and cancellation token. ```C# Task>> GetRedemptionRecordsAsync(LendingType lendingType, [Optional] string? asset, [Optional] DateTime? startTime, [Optional] DateTime? endTime, int? page, int? limit, [Optional] long? receiveWindow, [Optional] CancellationToken ct); ```