public static async Task Main(string[] args) { Crypto.Test(); return; cout("----------------------------"); cout("BinanceExchange API - Tester"); cout("----------------------------"); //Logging Configuration. //Ensure that `nlog.config` is configured as you want, and is copied to output directory. var loggerFactory = new LoggerFactory(); loggerFactory.AddNLog(new NLogProviderOptions { CaptureMessageTemplates = true, CaptureMessageProperties = true }); //This utilises the nlog.config from the build directory loggerFactory.ConfigureNLog("nlog.config"); //For the sakes of this example we are outputting only fatal logs, debug being the lowest. LogManager.GlobalThreshold = LogLevel.Fatal; var logger = LogManager.GetLogger("*"); //Provide your configuration and keys here, this allows the client to function as expected. //string apiPathname = @"\\vmware-host\Shared Folders\Downloads\crypto_api.txt"; string apiPathname = @"/Users/michael/Downloads/crypto_api.txt"; string[] lines = System.IO.File.ReadAllLines(apiPathname); string apiKey = lines[0]; // "YOUR_API_KEY"; string secretKey = lines[1]; // "YOUR_SECRET_KEY"; /*// ENTER A TRXETH SELL ORDER (the HARD way!!!) * //string str = "symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000×tamp=1499827319559"; * string timestamp = GetTimestamp(); * string str = "symbol=TRXETH&side=SELL&type=LIMIT&timeInForce=GTC&quantity=200&price=0.00011470&recvWindow=10000000×tamp=" + timestamp; * //string signature = CreateHMACSignature("NhqPtmdSJYdKjVHjA7PZj4Mge3R5YNiP1e3UZjInClVN65XAbvqqM6A7H5fATj0j", str); * string signature = CreateHMACSignature(secretKey, str); * cout(signature); * //string cmd = "curl - H \"X-MBX-APIKEY: vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A\" - X POST 'https://api.binance.com/api/v3/order?symbol=LTCBTC&side=BUY&type=LIMIT&timeInForce=GTC&quantity=1&price=0.1&recvWindow=5000×tamp=1499827319559&signature=" + signature + "'"; * //apiKey = "vmPUZE6mv9SD5VNHk4HlWFsOr6aKE2zvsw0MuIgwCIPy6utIco14y7Ju91duEh8A"; * string cmd = "curl -H \"X-MBX-APIKEY: " + apiKey + "\" -X POST 'https://api.binance.com/api/v3/order?" + str + "&signature=" + signature + "'"; * cout(cmd); * string result = Bash(cmd); * System.Console.WriteLine("\n{0}", result); * return;*/ //Initialise the general client client with config client = new BinanceClient(new ClientConfiguration() { ApiKey = apiKey, SecretKey = secretKey, Logger = logger, }); cout("Interacting with Binance..."); bool DEBUG_ALL = true; /* * Code Examples - Make sure you adjust value of DEBUG_ALL */ if (DEBUG_ALL) { int i; // ---TEST CLIENT CONNECTION--- await client.TestConnectivity(); // ---ACCOUNT INFO--- var accountInfo = await client.GetAccountInformation(); var balances = accountInfo.Balances; balances.Where(s => s.Free != 0.0M || s.Locked != 0.0M).ToList().ForEach(cout); var canDeposit = accountInfo.CanDeposit; var canTrade = accountInfo.CanTrade; var canWithdraw = accountInfo.CanWithdraw; var buyerComm = accountInfo.BuyerCommission; var sellerComm = accountInfo.SellerCommission; var makerComm = accountInfo.MakerCommission; var takerComm = accountInfo.TakerCommission; cout("commissions buyer:{0} seller:{1} maker:{2} taker:{3}\npermissions deposit:{4} trade:{5} withdraw:{6}", buyerComm, sellerComm, makerComm, takerComm, canDeposit, canTrade, canWithdraw); // SYMBOL TO TRADE string symbol = TradingPairSymbols.ETHPairs.TRX_ETH; return; /*// Create an order with varying options * //var createOrder = await client.CreateOrder(new CreateOrderRequest() * var createOrder = await client.CreateTestOrder(new CreateOrderRequest() * { * //IcebergQuantity = 200, * Price = 0.00011470, * Quantity = 200, * Side = OrderSide.Sell, * Symbol = "TRXETH", * Type = OrderType.Limit, * TimeInForce = TimeInForce.GTC * });*/ /*// Get All Orders * cout("Getting all {0} orders...", symbol); * var allOrdersRequest = new AllOrdersRequest() * { * //Symbol = TradingPairSymbols.BTCPairs.ETH_BTC, * Symbol = symbol, * Limit = 50, * }; * var allOrders = await client.GetAllOrders(allOrdersRequest); // Get All Orders * i = 0; * foreach (var o in allOrders) * { * cout("{0}) {1}", ++i, OrderStr(o)); * }*/ // Get current open orders for the specified symbol cout("Getting open {0} orders...", symbol); var currentOpenOrders = await client.GetCurrentOpenOrders(new CurrentOpenOrdersRequest() { Symbol = symbol, }); i = 0; foreach (var o in currentOpenOrders) { cout("{0}) {1}", ++i, o.ToString()); } if (currentOpenOrders.Count > 0) { long lastOrderId = currentOpenOrders.FindLast(m => m.Symbol != null).OrderId; // TODO: The API docs seem to indicate these client order IDs can be strings like "MyOrder1" or "CancelMyOrder1" (?) // Cancel an order cout("Cancelling order..."); var co = new CancelOrderRequest() { //NewClientOrderId = "123456", //OrderId = 12136215, OrderId = lastOrderId, //OriginalClientOrderId = "23525", Symbol = symbol, }; var cancelOrder = await client.CancelOrder(co); } return; // Get the order book, and use the cache cout("Getting {0} order book...", symbol); var orderBook = await client.GetOrderBook(symbol, true); orderBook.Asks.Reverse(); foreach (var o in orderBook.Asks) { //cout(OrderStr(o)); } cout("---------"); foreach (var o in orderBook.Bids) { //cout(OrderStr(o)); } /*// Cancel an order * var cancelOrder = await client.CancelOrder(new CancelOrderRequest() * { * NewClientOrderId = 123456, * OrderId = 523531, * OriginalClientOrderId = 23525, * Symbol = "ETHBTC", * });*/ // Get account information cout("Getting {0} account information...", symbol); var accountInformation = await client.GetAccountInformation(); //3500); cout("Account Information:"); cout("CanTrade:{0} CanDeposit:{1} CanWithdraw:{2}", accountInformation.CanTrade, accountInformation.CanDeposit, accountInformation.CanWithdraw); System.Console.WriteLine("Commissions buyer:{0} seller:{1} maker:{2} taker:{3}", accountInformation.BuyerCommission, accountInformation.SellerCommission, accountInformation.MakerCommission, accountInformation.TakerCommission); System.Console.WriteLine("Balances:"); foreach (var balance in accountInformation.Balances) { if (balance.Free != 0 || balance.Locked != 0) { System.Console.WriteLine("{0} free:{1} locked:{2}", balance.Asset, balance.Free, balance.Locked); } } System.Console.WriteLine(""); return; // Get account trades var accountTrades = await client.GetAccountTrades(new AllTradesRequest() { FromId = 352262, Symbol = symbol, }); // Get a list of Compressed aggregate trades with varying options var aggTrades = await client.GetCompressedAggregateTrades(new GetCompressedAggregateTradesRequest() { StartTime = DateTime.UtcNow.AddDays(-1), Symbol = symbol, }); /*// Get current open orders for the specified symbol * var currentOpenOrders = await client.GetCurrentOpenOrders(new CurrentOpenOrdersRequest() * { * Symbol = symbol, * });*/ // Get daily ticker var dailyTicker = await client.GetDailyTicker(symbol); // Get Symbol Order Book Ticker var symbolOrderBookTicker = await client.GetSymbolOrderBookTicker(); // Get Symbol Order Price Ticker var symbolOrderPriceTicker = await client.GetSymbolsPriceTicker(); // Query a specific order on Binance var orderQuery = await client.QueryOrder(new QueryOrderRequest() { OrderId = 5425425, Symbol = symbol, }); // Firing off a request and catching all the different exception types. try { accountTrades = await client.GetAccountTrades(new AllTradesRequest() { FromId = 352262, Symbol = "ETHBTC", }); } catch (BinanceBadRequestException badRequestException) { } catch (BinanceServerException serverException) { } catch (BinanceTimeoutException timeoutException) { } catch (BinanceException unknownException) { } } // Start User Data Stream, ping and close var userData = await client.StartUserDataStream(); await client.KeepAliveUserDataStream(userData.ListenKey); await client.CloseUserDataStream(userData.ListenKey); return; // Manual WebSocket usage var manualBinanceWebSocket = new InstanceBinanceWebSocketClient(client); var socketId = manualBinanceWebSocket.ConnectToDepthWebSocket("ETHBTC", b => { System.Console.Clear(); System.Console.WriteLine($"{JsonConvert.SerializeObject(b.BidDepthDeltas, Formatting.Indented)}"); System.Console.SetWindowPosition(0, 0); }); #region Advanced Examples // This builds a local Kline cache, with an initial call to the API and then continues to fill // the cache with data from the WebSocket connection. It is quite an advanced example as it provides // additional options such as an Exit Func<T> or timeout, and checks in place for cache instances. // You could provide additional logic here such as populating a database, ping off more messages, or simply // timing out a fill for the cache. var dict = new Dictionary <string, KlineCacheObject>(); //await BuildAndUpdateLocalKlineCache(client, "BNBBTC", KlineInterval.OneMinute, // new GetKlinesCandlesticksRequest() // { // StartTime = DateTime.UtcNow.AddHours(-1), // EndTime = DateTime.UtcNow, // Interval = KlineInterval.OneMinute, // Symbol = "BNBBTC" // }, new WebSocketConnectionFunc(15000), dict); // This builds a local depth cache from an initial call to the API and then continues to fill // the cache with data from the WebSocket var localDepthCache = await BuildLocalDepthCache(client); // Build the Buy Sell volume from the results var volume = ResultTransformations.CalculateTradeVolumeFromDepth("BNBBTC", localDepthCache); #endregion System.Console.WriteLine("Complete."); Thread.Sleep(6000); manualBinanceWebSocket.CloseWebSocketInstance(socketId); System.Console.ReadLine(); }
public static async Task Main(string[] args) { //Provide your configuration and keys here, this allows the client to function as expected. string apiKey = "YOUR_API_KEY"; string secretKey = "YOUR_SECRET_KEY"; System.Console.WriteLine("--------------------------"); System.Console.WriteLine("BinanceExchange API - Tester"); System.Console.WriteLine("--------------------------"); //Building a test logger var exampleProgramLogger = LogManager.GetLogger(typeof(ExampleProgram)); exampleProgramLogger.Debug("Logging Test"); //Initialise the general client client with config var client = new BinanceClient(new ClientConfiguration() { ApiKey = apiKey, SecretKey = secretKey, Logger = exampleProgramLogger, }); System.Console.WriteLine("Interacting with Binance..."); bool DEBUG_ALL = false; /* * Code Examples - Make sure you adjust value of DEBUG_ALL */ if (DEBUG_ALL) { // Test the Client await client.TestConnectivity(); // Get All Orders var allOrdersRequest = new AllOrdersRequest() { Symbol = "ETHBTC", Limit = 5, }; allOrdersRequest = new AllOrdersRequest() { Symbol = TradingPairSymbols.BTCPairs.ETH_BTC, Limit = 5, }; // Get All Orders var allOrders = await client.GetAllOrders(allOrdersRequest); // Get the order book, and use the cache var orderBook = await client.GetOrderBook("ETHBTC", true); // Cancel an order var cancelOrder = await client.CancelOrder(new CancelOrderRequest() { NewClientOrderId = "123456", OrderId = 523531, OriginalClientOrderId = "789", Symbol = "ETHBTC", }); // Create an order with varying options var createOrder = await client.CreateOrder(new CreateOrderRequest() { IcebergQuantity = 100, Price = 230, Quantity = 0.6m, Side = OrderSide.Buy, Symbol = "ETHBTC", Type = OrderType.Market, }); // Get account information var accountInformation = await client.GetAccountInformation(3500); // Get account trades var accountTrades = await client.GetAccountTrades(new AllTradesRequest() { FromId = 352262, Symbol = "ETHBTC", }); // Get a list of Compressed aggregate trades with varying options var aggTrades = await client.GetCompressedAggregateTrades(new GetCompressedAggregateTradesRequest() { StartTime = DateTime.UtcNow.AddDays(-1), Symbol = "ETHBTC", }); // Get current open orders for the specified symbol var currentOpenOrders = await client.GetCurrentOpenOrders(new CurrentOpenOrdersRequest() { Symbol = "ETHBTC", }); // Get daily ticker var dailyTicker = await client.GetDailyTicker("ETHBTC"); // Get Symbol Order Book Ticket var symbolOrderBookTicker = await client.GetSymbolOrderBookTicker(); // Get Symbol Order Price Ticker var symbolOrderPriceTicker = await client.GetSymbolsPriceTicker(); // Query a specific order on Binance var orderQuery = await client.QueryOrder(new QueryOrderRequest() { OrderId = 5425425, Symbol = "ETHBTC", }); // Firing off a request and catching all the different exception types. try { accountTrades = await client.GetAccountTrades(new AllTradesRequest() { FromId = 352262, Symbol = "ETHBTC", }); } catch (BinanceBadRequestException badRequestException) { } catch (BinanceServerException serverException) { } catch (BinanceTimeoutException timeoutException) { } catch (BinanceException unknownException) { } } // Start User Data Stream, ping and close var userData = await client.StartUserDataStream(); await client.KeepAliveUserDataStream(userData.ListenKey); await client.CloseUserDataStream(userData.ListenKey); // Manual WebSocket usage var manualBinanceWebSocket = new InstanceBinanceWebSocketClient(client); var socketId = manualBinanceWebSocket.ConnectToDepthWebSocket("ETHBTC", b => { System.Console.Clear(); System.Console.WriteLine($"{JsonConvert.SerializeObject(b.BidDepthDeltas, Formatting.Indented)}"); System.Console.SetWindowPosition(0, 0); }); #region Advanced Examples // This builds a local Kline cache, with an initial call to the API and then continues to fill // the cache with data from the WebSocket connection. It is quite an advanced example as it provides // additional options such as an Exit Func<T> or timeout, and checks in place for cache instances. // You could provide additional logic here such as populating a database, ping off more messages, or simply // timing out a fill for the cache. var dict = new Dictionary <string, KlineCacheObject>(); //await BuildAndUpdateLocalKlineCache(client, "BNBBTC", KlineInterval.OneMinute, // new GetKlinesCandlesticksRequest() // { // StartTime = DateTime.UtcNow.AddHours(-1), // EndTime = DateTime.UtcNow, // Interval = KlineInterval.OneMinute, // Symbol = "BNBBTC" // }, new WebSocketConnectionFunc(15000), dict); // This builds a local depth cache from an initial call to the API and then continues to fill // the cache with data from the WebSocket var localDepthCache = await BuildLocalDepthCache(client); // Build the Buy Sell volume from the results var volume = ResultTransformations.CalculateTradeVolumeFromDepth("BNBBTC", localDepthCache); #endregion System.Console.WriteLine("Complete."); Thread.Sleep(6000); manualBinanceWebSocket.CloseWebSocketInstance(socketId); System.Console.ReadLine(); }
public static async Task Main() { //Provide your configuration and keys here, this allows the client to function as expected. //k: //sk: string apiKey = ""; string secretKey = ""; System.Console.WriteLine("--------------------------"); System.Console.WriteLine("BinanceExchange API - Tester"); System.Console.WriteLine("--------------------------"); //Building a test logger var exampleProgramLogger = LogManager.GetLogger(typeof(ExampleProgram)); exampleProgramLogger.Debug("Logging Test"); //Initialise the general client client with config var client = new BinanceClient(new ClientConfiguration() { ApiKey = apiKey, SecretKey = secretKey, Logger = exampleProgramLogger, }); Console.WriteLine(client); Console.WriteLine(apiKey); System.Console.WriteLine("Interacting with Binance..."); bool DEBUG_ALL = true; /* * Code Examples - Make sure you adjust value of DEBUG_ALL */ if (DEBUG_ALL) { // Test the Client await client.TestConnectivity(); // Get All Orders var allOrdersRequest = new AllOrdersRequest() { Symbol = "ETHBTC", Limit = 5, }; allOrdersRequest = new AllOrdersRequest() { Symbol = TradingPairSymbols.BTCPairs.ETH_BTC, Limit = 5, }; // Get All Orders //var allOrders = await client.GetAllOrders(allOrdersRequest); // Get the order book, and use the cache //var orderBook = await client.GetOrderBook("ETHBTC", true); // Cancel an order /* * var cancelOrder = await client.CancelOrder(new CancelOrderRequest() * { * NewClientOrderId = "123456", * OrderId = 523531, * OriginalClientOrderId = "789", * Symbol = "ETHBTC", * }); * * // Create an order with varying options * var createOrder = await client.CreateOrder(new CreateOrderRequest() * { * IcebergQuantity = 100, * Price = 230, * Quantity = 0.6m, * Side = OrderSide.Buy, * Symbol = "ETHBTC", * Type = OrderType.Market, * }); */ // Get account information var accountInformation = await client.GetAccountInformation(3500); // Get account trades var accountTrades = await client.GetAccountTrades(new AllTradesRequest() { FromId = 352262, Symbol = "ETHBTC", }); /* * // Get a list of Compressed aggregate trades with varying options * var aggTrades = await client.GetCompressedAggregateTrades(new GetCompressedAggregateTradesRequest() * { * StartTime = DateTime.UtcNow.AddDays(-1), * Symbol = "ETHBTC", * }); * * // Get current open orders for the specified symbol * var currentOpenOrders = await client.GetCurrentOpenOrders(new CurrentOpenOrdersRequest() * { * Symbol = "ETHBTC", * }); */ // Get daily ticker ExampleProgram ep = new ExampleProgram(); ep.CoinBalance = 0.000000; ep.USDBalance = 100.00; ep.PreviousCost = 0.0255; var dailyTicker = await client.GetDailyTicker("TRXUSDT"); var symbolOrderBookTicker = await client.GetSymbolOrderBookTicker(); var symbolOrderPriceTicker = await client.GetSymbolsPriceTicker(); while (true) { dailyTicker = await client.GetDailyTicker("TRXUSDT"); // Get Symbol Order Book Ticket symbolOrderBookTicker = await client.GetSymbolOrderBookTicker(); // Get Symbol Order Price Ticker symbolOrderPriceTicker = await client.GetSymbolsPriceTicker(); //get new sell target ep.SellTarget = ep.GetSellTarget((decimal)ep.PreviousCost, (decimal)ep.TradeFee); //get new buy target ep.BuyTarget = ep.GetBuyTarget((decimal)ep.PreviousCost, (decimal)ep.TradeFee); //If Buy Target Hit if (dailyTicker.AskPrice <= Convert.ToDecimal(ep.BuyTarget)) { ep.AvailableToBuy = ep.calculateAvailableToBuy(ep.USDBalance, dailyTicker.AskPrice); // if available to buy > 1 if (ep.AvailableToBuy > 1) { // buy, update all vars, ep.Buy(dailyTicker.AskPrice); } } //if sell target hit if (dailyTicker.AskPrice >= Convert.ToDecimal(ep.SellTarget)) { // if available to sell > 1 if (ep.CoinBalance >= 1) { // sell, update all vars ep.Sell(dailyTicker.AskPrice); } } Console.Clear(); Console.WriteLine("Ask Price: " + dailyTicker.AskPrice); Console.WriteLine("Bid Price: " + dailyTicker.BidPrice); Console.WriteLine("Last Price: " + dailyTicker.LastPrice); Console.WriteLine("Open Price: " + dailyTicker.OpenPrice); Console.WriteLine("Prev Close Price: " + dailyTicker.PreviousClosePrice); Console.WriteLine(); Console.WriteLine("lastCost: " + ep.PreviousCost); Console.WriteLine("Buy Target: " + ep.BuyTarget); Console.WriteLine("Sell Target: " + ep.SellTarget); Console.WriteLine("======================= BALANCES ============================"); Console.WriteLine("Coins: " + ep.CoinBalance); Console.WriteLine("Fees Paid: " + ep.FeePaid); Console.WriteLine("USD: " + ep.USDBalance); Console.WriteLine("paid: " + ep.lastSpent); Console.WriteLine("made: " + ep.lastMade); Thread.Sleep(500); /* * if (dailyTicker.AskPrice > Convert.ToDecimal(ep.PreviousCost + (ep.PreviousCost * ep.TradeFee))) * { * * Console.WriteLine("Sell Target Hit"); * if (coinBalance > 0) * { * Console.WriteLine("Selling"); * lastCost = Convert.ToDouble(dailyTicker.AskPrice); * * usdBalance = (coinBalance * Convert.ToDouble(dailyTicker.AskPrice))-(coinBalance * Convert.ToDouble(dailyTicker.AskPrice)*.001); * coinBalance = 0; * //sell * //lastcost = askprice * } * } * if (dailyTicker.AskPrice < Convert.ToDecimal(ep.PreviousCost + (ep.PreviousCost * ep.TradeFee))) * { * Console.WriteLine("Buy Target Hit"); * if (usdBalance / (Convert.ToDouble(dailyTicker.AskPrice) * .001) > 0) * { * Console.WriteLine("Buying"); * lastCost = Convert.ToDouble(dailyTicker.AskPrice); * * coinBalance = usdBalance / (Convert.ToDouble(dailyTicker.AskPrice) + (Convert.ToDouble(dailyTicker.AskPrice)*.001)); * usdBalance -= (usdBalance / Convert.ToDouble(dailyTicker.AskPrice)) * .001; //coinBalance * (Convert.ToDouble(dailyTicker.AskPrice) * .001); * //buy * //last cost = askPrice * } * } */ } // Query a specific order on Binance var orderQuery = await client.QueryOrder(new QueryOrderRequest() { OrderId = 5425425, Symbol = "ETHBTC", }); // Firing off a request and catching all the different exception types. try { accountTrades = await client.GetAccountTrades(new AllTradesRequest() { FromId = 352262, Symbol = "ETHBTC", }); } catch (BinanceBadRequestException badRequestException) { } catch (BinanceServerException serverException) { } catch (BinanceTimeoutException timeoutException) { } catch (BinanceException unknownException) { } } // Start User Data Stream, ping and close var userData = await client.StartUserDataStream(); await client.KeepAliveUserDataStream(userData.ListenKey); await client.CloseUserDataStream(userData.ListenKey); // Manual WebSocket usage var manualBinanceWebSocket = new InstanceBinanceWebSocketClient(client); var socketId = manualBinanceWebSocket.ConnectToDepthWebSocket("ETHBTC", b => { System.Console.Clear(); System.Console.WriteLine($"{JsonConvert.SerializeObject(b.BidDepthDeltas, Formatting.Indented)}"); System.Console.SetWindowPosition(0, 0); }); #region Advanced Examples // This builds a local Kline cache, with an initial call to the API and then continues to fill // the cache with data from the WebSocket connection. It is quite an advanced example as it provides // additional options such as an Exit Func<T> or timeout, and checks in place for cache instances. // You could provide additional logic here such as populating a database, ping off more messages, or simply // timing out a fill for the cache. var dict = new Dictionary <string, KlineCacheObject>(); //await BuildAndUpdateLocalKlineCache(client, "BNBBTC", KlineInterval.OneMinute, // new GetKlinesCandlesticksRequest() // { // StartTime = DateTime.UtcNow.AddHours(-1), // EndTime = DateTime.UtcNow, // Interval = KlineInterval.OneMinute, // Symbol = "BNBBTC" // }, new WebSocketConnectionFunc(15000), dict); // This builds a local depth cache from an initial call to the API and then continues to fill // the cache with data from the WebSocket var localDepthCache = await BuildLocalDepthCache(client); // Build the Buy Sell volume from the results var volume = ResultTransformations.CalculateTradeVolumeFromDepth("BNBBTC", localDepthCache); #endregion System.Console.WriteLine("Complete."); Thread.Sleep(6000); manualBinanceWebSocket.CloseWebSocketInstance(socketId); System.Console.ReadLine(); }