コード例 #1
0
        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();
        }
コード例 #2
0
 static void Main(string[] args)
 {
     ExampleProgram.Main().Wait();
 }