
Security News
PHP Foundation Says Chainguard Broke Security Embargo Ahead of Emergency Patches
The PHP Foundation says Chainguard broke a security embargo ahead of critical RCE patches, as leaks disrupted the coordinated release.
Binance.Csharp
Advanced tools
This is a lightweight library that works as a connector to Binance public API
/api/*/sapi/*dotnet add package Binance.Csharp
Usage example
using System;
using System.Threading.Tasks;
using BinanceCsharp;
class Program
{
static async Task Main(string[] args)
{
Market market = new Market();
string serverTime = await market.CheckServerTime();
Console.WriteLine(serverTime);
}
}
Please find APIExamples folder to check for more endpoints.
Usage Example
using System;
using System.Threading;
using System.Threading.Tasks;
using BinanceCsharp;
class Program
{
static async Task Main(string[] args)
{
var websocket = new MarketDataWebSocket("btcusdt@aggTrade");
websocket.OnMessageReceived(
(data) =>
{
Console.WriteLine(data);
return Task.CompletedTask;
}, CancellationToken.None);
await websocket.ConnectAsync(CancellationToken.None);
}
}
More websocket examples are available in the APIExamples folder
Usage Example
using System.Threading;
using System.Threading.Tasks;
using Binance.Common;
using BinanceCsharp;
public class NewOrder_Example
{
public static async Task Main(string[] args)
{
var websocket = new WebSocketApi("wss://ws-api.testnet.binance.vision/ws-api/v3", "apiKey", new BinanceHmac("apiSecret"));
websocket.OnMessageReceived(
async (data) =>
{
Console.WriteLine(data);
await Task.CompletedTask;
}, CancellationToken.None);
await websocket.ConnectAsync(CancellationToken.None);
await websocket.AccountTrade.NewOrderAsync(symbol: "BNBUSDT", side: Models.Side.BUY, type: Models.OrderType.LIMIT, timeInForce: Models.TimeInForce.GTC, price: 300, quantity: 1, cancellationToken: CancellationToken.None);
await Task.Delay(5000);
Console.WriteLine("Disconnect with WebSocket API Server");
await websocket.DisconnectAsync(CancellationToken.None);
}
}
requestId param is optional. If not sent, it defaults to a randomly created GUID (Globally Unique Identifier).cancellationToken is optional. If not sent, it defaults to CancellationToken.None.More websocket API examples are available in the APIExamples folder
For API endpoints that requires signature, new authentication interfaces are introduced to generate the signature since V2.
// HMAC signature
new SpotAccountTrade(httpClient, new BinanceHmac("apiSecret"), apiKey: "apiKey")
// RSA signature
string privateKey = File.ReadAllText("/Users/john/ssl/PrivateKey.pem");
new SpotAccountTrade(httpClient, new BinanceRsa(privateKey), apiKey: "apiKey")
// Encrypted RSA signature
new SpotAccountTrade(httpClient, new BinanceRsa(privateKey, "thePrivateKeyPassword"), apiKey: "apiKey")
For V1.x, it's required to pass apiKey and apiSecret directly.
new SpotAccountTrade(httpClient, apiKey: apiKey, apiSecret: apiSecret)
For more details, please find the example from the endpoints /api/v3/account in file AccountInformation_Example.
// HMAC signature
new WebSocketApi(apiKey: "apiKey", signatureService: new BinanceHmac("apiSecret"));
// RSA signature
string privateKey = File.ReadAllText("/Users/john/ssl/PrivateKey.pem");
new WebSocketApi(apiKey: "apiKey", signatureService: new BinanceRsa(privateKey));
// Encrypted RSA signature
new WebSocketApi(apiKey: "apiKey", signatureService: new BinanceRsa(privateKey, "thePrivateKeyPassword"));
Once connected, the websocket server sends a ping frame every 3 minutes and requires a response pong frame back within a 10 minutes period. This package handles the pong responses automatically.
Spot Testnet can be used to test /api/* endpoints, Spot Websocket Stream and WebSocket API.
using BinanceCsharp;
Wallet wallet = new Wallet(baseUrl: "https://testnet.binance.vision");
If baseUrl is not provided, it defaults to https://api.binance.com.
It's recommended to pass in the baseUrl parameter, even in production as Binance provides alternative URLs
in case of performance issues:
https://api1.binance.comhttps://api2.binance.comhttps://api3.binance.comhttps://api4.binance.comFor Websocket Stream, baseUrl defaults to wss://stream.binance.com:9443".
For Websocket API, baseUrl defaults to wss://ws-api.binance.com:443/ws-api/v3.
Additional parameter recvWindow is available for endpoints requiring signature.
It defaults to 5000 (milliseconds) and can be any value lower than 60000(milliseconds).
Anything beyond the limit will result in an error response from Binance server.
using BinanceCsharp;
Wallet wallet = new Wallet();
await wallet.AccountStatus(recvWindow=4000)
The default timeout is 100,000 milliseconds (100 seconds).
Usage Example
using System;
using System.Net.Http;
using BinanceCsharp;
HttpClient httpClient = new HttpClient() {
Timeout = TimeSpan.FromSeconds(10)
}
Wallet wallet = new Wallet(httpClient: httpClient);
Usage Example
using System;
using System.Net;
using System.Net.Http;
using BinanceCsharp;
WebProxy proxy = new WebProxy(new Uri("http://1.2.3.4:8080"));
HttpClientHandler proxyHandler = new HttpClientHandler { Proxy = proxy };
HttpClient httpClient = new HttpClient(handler: proxyHandler);
Wallet wallet = new Wallet(httpClient: httpClient);
There are 2 types of exceptions returned from the library:
Binance.Common.BinanceClientException
4XX, it's an issue from client side.Code - Server's error code, e.g. -1102Message - Server's error message, e.g. Unknown order sent.Binance.Common.BinanceServerException
5XX, it's an issue from server side.Both exceptions inherit Binance.Common.BinanceHttpException along with the following properties:
StatusCode - Response http status code, e.g. 401Headers - Dictionary with response headersThis library implements the .NET logging API that works with a variety of built-in and third-party logging providers.
For more information on how to configure logging in .NET, visit Microsoft's logging article
Usage Example
using System;
using System.Net;
using System.Net.Http;
using BinanceCsharp;
public async Task LoggingExample(ILogger logger) {
BinanceLoggingHandler loggingHandler = new BinanceLoggingHandler(logger: logger);
HttpClient httpClient = new HttpClient(handler: loggingHandler);
Wallet wallet = new Wallet(httpClient: httpClient);
await wallet.SystemStatus();
}
Sample Output
Method: GET, RequestUri: 'https://www.binance.com/?timestamp=1631525776809&signature=f07558c98cb82bcb3556a6a21b8a8a2582bae93d0bb9604a0df72cae8c1c6642', Version: 1.1, Content: <null>, Headers: { }
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: <null>, Headers: {}
{"status": 0,"msg": "normal"}
dotnet test
FAQs
Binance API Csharp Library
We found that Binance.Csharp demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.

Security News
The PHP Foundation says Chainguard broke a security embargo ahead of critical RCE patches, as leaks disrupted the coordinated release.

Security News
PHP releases emergency patches for two critical RCE vulnerabilities as agencies urge organizations to take unpatched sites offline.

Threat Research
/Security News
A supply chain attack compromised LiteLLM 1.107.0 on PyPI and Docker, spreading malware that steals cloud credentials, developer secrets, and AI provider keys.