read data from binance in csharp

To read data from Binance in C#, you can use the Binance API which provides Rest API endpoints that return data in JSON format. Here is a code example using HttpClient to perform a GET request and retrieve the last trades for a symbol:

main.cs
using System;
using System.Collections.Generic;
using System.Net.Http;

namespace BinanceAPIExample
{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            using (var httpClient = new HttpClient())
            {
                var symbol = "BTCUSDT"; // The symbol you want to get trades for
                var limit = 10; // The maximum number of trades to retrieve

                var response = await httpClient.GetAsync($"https://api.binance.com/api/v3/trades?symbol={symbol}&limit={limit}");

                if (!response.IsSuccessStatusCode)
                {
                    Console.WriteLine($"Failed to retrieve trades. Status code: {response.StatusCode}");
                    return;
                }

                var jsonString = await response.Content.ReadAsStringAsync();

                // Deserialize the JSON response to a list of trades
                var trades = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Trade>>(jsonString);

                // Print the trades to the console
                foreach (var trade in trades)
                {
                    Console.WriteLine($"{trade.Price} {trade.Quantity}");
                }
            }
        }
    }

    public class Trade
    {
        public long Id { get; set; }
        public decimal Price { get; set; }
        public decimal Quantity { get; set; }
        // Define other trade properties here as needed
    }
}
1489 chars
46 lines

This code creates an HTTP client and performs a GET request to the Binance API endpoint https://api.binance.com/api/v3/trades with query parameters for the symbol and limit. If the response is successful, the JSON response is deserialized to a list of trades using the Newtonsoft.Json package. Finally, the trades are printed to the console.

gistlibby LogSnag