Beispiel #1
0
 public static void Monitor(BinanceClient client, InstanceBinanceWebSocketClient ws, List <OrderResponse> stopLossOrders)
 {
     foreach (var order in stopLossOrders)
     {
         Monitor(client, ws, order);
     }
 }
        static async Task MainAsync()
        {
            try
            {
                var client = new BinanceClient(new ClientConfiguration
                {
                    ApiKey    = Properties.Settings.Default.ApiKey,
                    SecretKey = Properties.Settings.Default.SecretKey
                });

                var ws = new InstanceBinanceWebSocketClient(client);

                Console.WriteLine($"{nameof(MainAsync)}: {DateTime.Now:O} Getting currently open orders...");
                var openOrders = await client.GetCurrentOpenOrders(new CurrentOpenOrdersRequest(), Properties.Settings.Default.ReceiveWindow);

                Console.WriteLine($"{nameof(MainAsync)}: {DateTime.Now:O} Found {openOrders.Count} open orders");

                var stopLossOrders = openOrders.Where(o => o.Type == OrderType.StopLoss || o.Type == OrderType.StopLossLimit).ToList();
                Console.WriteLine($"{nameof(MainAsync)}: {DateTime.Now:O} Found {stopLossOrders.Count} open {OrderType.StopLoss}/{OrderType.StopLossLimit} orders");

                OpenOrderProcessor.Manager.Monitor(client, ws, stopLossOrders);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            //try
            //{
            //    IKernel kernel = new StandardKernel();
            //    UOWRegistration.BindAll(kernel);
            //    uow = kernel.Get<IUnitOfWork>();
            //}
            //catch (Exception ex) { Console.WriteLine("Error on Application Start:   " + ex.Message); }

            //var obj = new PolygonWebConnect();
            //obj.Start();

            var client = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = "9fc2M7WrNl6FdsEv9Pk80eGXy68bZgtUscp1oOPX6w2cnOKQyGdvrtoEAox9gQR2",
                SecretKey = "fS7RG3om3ChfRI2JpD5cV1Qj2ZWwIvG8ANtRlrluDqSRVmz6bzDgS3CR5T0qp2gf",
            });

            var manualWebSocketClient = new InstanceBinanceWebSocketClient(client);
            var socketId = manualWebSocketClient.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.OneMinute, data =>
            {
                System.Console.WriteLine($"1 Minute:  {JsonConvert.SerializeObject(data)}");
            });

            var manualWebSocketClient2 = new InstanceBinanceWebSocketClient(client);
            var socketId2 = manualWebSocketClient2.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.OneHour, data =>
            {
                System.Console.WriteLine($"1 Hour:  {JsonConvert.SerializeObject(data)}");
            });

            //manualWebSocketClient.CloseWebSocketInstance(socketId);

            Console.ReadKey();
        }
Beispiel #4
0
 public Strategy_Phase1()
 {
     userDATA        = new BinaDataUser();
     depthDATA       = new BinaDataDepth();
     webSocketClient = new InstanceBinanceWebSocketClient(BinaREST.client);
     OpenBUYorders   = new List <OrderInfo>();
     OpenSELLorders  = new List <OrderInfo>();
     StrategyP2      = new Strategy_Phase2(SETTINGS.SubSpecificSymbols[0], PriceRoundDigits, QtyRoundDigits);
 }
Beispiel #5
0
        static void Main()
        {
            var apiKey    = "test";
            var secretKey = "test";

            var client = new BinanceClient(new ClientConfiguration
            {
                ApiKey    = apiKey,
                SecretKey = secretKey
            });

            Console.WriteLine("Interacting with Binance...");

            var binanceWebSocketClient = new InstanceBinanceWebSocketClient(client);
            var webSocketGuid          = Guid.Empty;

            try
            {
                webSocketGuid = binanceWebSocketClient.ConnectToTradesWebSocket("ETHBTC", data =>
                {
                    using (var db = new ApplicationContext())
                    {
                        db.Trades.Add(Mapper.Map(data));
                        db.SaveChanges();
                    }
                });

                while (binanceWebSocketClient.IsAlive(webSocketGuid))
                {
                    //Ждем получения
                }
            }
            finally
            {
                Console.WriteLine("Stopped.");
                binanceWebSocketClient.CloseWebSocketInstance(webSocketGuid);
            }
        }
Beispiel #6
0
            public static void Monitor(BinanceClient client, InstanceBinanceWebSocketClient ws, OrderResponse orderResponse)
            {
                if (!(orderResponse.Type == OrderType.StopLoss || orderResponse.Type == OrderType.StopLossLimit))
                {
                    return;
                }

                Processors.GetOrAdd(orderResponse.OrderId, _ =>
                {
                    Console.WriteLine($"{nameof(Monitor)}: {DateTime.Now:O} {orderResponse.Symbol} Monitoring '{orderResponse.OrderId}' for {orderResponse.OriginalQuantity - orderResponse.ExecutedQuantity:N8} @ {orderResponse.StopPrice:N8}");

                    var processor = new OpenOrderProcessor(client, orderResponse);
                    var monitoredSymbolsProcessors = MonitoredSymbols.GetOrAdd(orderResponse.Symbol, symbol =>
                    {
                        Monitor(ws, symbol);
                        return(new HashSet <OpenOrderProcessor> {
                            processor
                        });
                    });
                    monitoredSymbolsProcessors.Add(processor);
                    return(processor);
                });
            }
Beispiel #7
0
        static void Main(string[] args)
        {
            BinanceKlineData Minute        = null;
            BinanceKlineData FiveMinute    = null;
            BinanceKlineData FifteenMinute = null;
            BinanceKlineData ThirtyMinute  = null;
            BinanceKlineData Hour          = null;
            BinanceKlineData Day           = null;

            BinanceKlineData MinuteETH        = null;
            BinanceKlineData FiveMinuteETH    = null;
            BinanceKlineData FifteenMinuteETH = null;
            BinanceKlineData ThirtyMinuteETH  = null;
            BinanceKlineData HourETH          = null;
            BinanceKlineData DayETH           = null;

            BinanceKlineData MinuteLTC        = null;
            BinanceKlineData FiveMinuteLTC    = null;
            BinanceKlineData FifteenMinuteLTC = null;
            BinanceKlineData ThirtyMinuteLTC  = null;
            BinanceKlineData HourLTC          = null;
            BinanceKlineData DayLTC           = null;

            BinanceKlineData MinuteXRP        = null;
            BinanceKlineData FiveMinuteXRP    = null;
            BinanceKlineData FifteenMinuteXRP = null;
            BinanceKlineData ThirtyMinuteXRP  = null;
            BinanceKlineData HourXRP          = null;
            BinanceKlineData DayXRP           = null;

            /////////////// Main ////////////////////
            var ApiKey    = "TdRGlhtg7RsuQG6MPmbKvasd2EOMFBopLIVLmeAsoIRq5Q03qeCZwAOUCqjLhYIO";
            var SecretKey = "45gClX8cfTo2zUezse6ETFdH1kMO44OnqdgaZEHve3nu1vRLWpI26ku52yjS9odt";

            //////////////// Test ////////////////////
            //var ApiKey = "9fc2M7WrNl6FdsEv9Pk80eGXy68bZgtUscp1oOPX6w2cnOKQyGdvrtoEAox9gQR2";
            //var SecretKey = "fS7RG3om3ChfRI2JpD5cV1Qj2ZWwIvG8ANtRlrluDqSRVmz6bzDgS3CR5T0qp2gf";

            var client = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client1 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client2 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client3 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client4 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client5 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client6 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client7 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client8 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client9 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client10 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client11 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client12 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client13 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client14 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client15 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client16 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client17 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client18 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client19 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client20 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client21 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client22 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            var client23 = new BinanceClient(new ClientConfiguration()
            {
                ApiKey    = ApiKey,
                SecretKey = SecretKey,
            });

            Console.WriteLine("WebSocket Syncing Start...");
            ///////////////////////////////////////////////////////////////
            Thread WebSocketSyncing = new Thread(() =>
            {
                var manualWebSocketClient   = new InstanceBinanceWebSocketClient(client);
                var manualWebSocketClient2  = new InstanceBinanceWebSocketClient(client1);
                var manualWebSocketClient20 = new InstanceBinanceWebSocketClient(client2);
                var manualWebSocketClient3  = new InstanceBinanceWebSocketClient(client3);
                var manualWebSocketClient21 = new InstanceBinanceWebSocketClient(client4);
                var manualWebSocketClient22 = new InstanceBinanceWebSocketClient(client5);
                var manualWebSocketClient6  = new InstanceBinanceWebSocketClient(client6);
                var manualWebSocketClient7  = new InstanceBinanceWebSocketClient(client7);
                var manualWebSocketClient8  = new InstanceBinanceWebSocketClient(client8);
                var manualWebSocketClient23 = new InstanceBinanceWebSocketClient(client9);
                var manualWebSocketClient24 = new InstanceBinanceWebSocketClient(client10);
                var manualWebSocketClient25 = new InstanceBinanceWebSocketClient(client11);
                var manualWebSocketClient11 = new InstanceBinanceWebSocketClient(client12);
                var manualWebSocketClient12 = new InstanceBinanceWebSocketClient(client13);
                var manualWebSocketClient13 = new InstanceBinanceWebSocketClient(client14);
                var manualWebSocketClient26 = new InstanceBinanceWebSocketClient(client15);
                var manualWebSocketClient27 = new InstanceBinanceWebSocketClient(client16);
                var manualWebSocketClient28 = new InstanceBinanceWebSocketClient(client17);
                var manualWebSocketClient16 = new InstanceBinanceWebSocketClient(client18);
                var manualWebSocketClient17 = new InstanceBinanceWebSocketClient(client19);
                var manualWebSocketClient18 = new InstanceBinanceWebSocketClient(client20);
                var manualWebSocketClient29 = new InstanceBinanceWebSocketClient(client21);
                var manualWebSocketClient30 = new InstanceBinanceWebSocketClient(client22);
                var manualWebSocketClient31 = new InstanceBinanceWebSocketClient(client23);

                try
                {
                    var socketId = manualWebSocketClient.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.OneMinute, data =>
                    {
                        try
                        {
                            Minute = data;
                        }
                        catch (Exception) {
                            Environment.Exit(0);
                        }
                    });

                    var socketId2 = manualWebSocketClient2.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.OneHour, data =>
                    {
                        try
                        {
                            Hour = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId3 = manualWebSocketClient3.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.OneDay, data =>
                    {
                        try {
                            Day = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId20 = manualWebSocketClient20.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.FiveMinutes, data =>
                    {
                        try {
                            FiveMinute = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId21 = manualWebSocketClient21.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.FifteenMinutes, data =>
                    {
                        try {
                            FifteenMinute = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId22 = manualWebSocketClient22.ConnectToKlineWebSocket("BTCUSDT", KlineInterval.ThirtyMinutes, data =>
                    {
                        try {
                            ThirtyMinute = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    /////////////////////////////////////////////////////////////////////////////////////////////////////////////
                    var socketId6 = manualWebSocketClient6.ConnectToKlineWebSocket("ETHUSDT", KlineInterval.OneMinute, data =>
                    {
                        try {
                            MinuteETH = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId7 = manualWebSocketClient7.ConnectToKlineWebSocket("ETHUSDT", KlineInterval.OneHour, data =>
                    {
                        try {
                            HourETH = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId8 = manualWebSocketClient8.ConnectToKlineWebSocket("ETHUSDT", KlineInterval.OneDay, data =>
                    {
                        try {
                            DayETH = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId23 = manualWebSocketClient23.ConnectToKlineWebSocket("ETHUSDT", KlineInterval.FiveMinutes, data =>
                    {
                        try {
                            FiveMinuteETH = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId24 = manualWebSocketClient24.ConnectToKlineWebSocket("ETHUSDT", KlineInterval.FifteenMinutes, data =>
                    {
                        try {
                            FifteenMinuteETH = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId25 = manualWebSocketClient25.ConnectToKlineWebSocket("ETHUSDT", KlineInterval.ThirtyMinutes, data =>
                    {
                        try {
                            ThirtyMinuteETH = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    ////////////////////////////////  LTC-USDT  ////////////////////////////////////////
                    var socketId11 = manualWebSocketClient11.ConnectToKlineWebSocket("LTCUSDT", KlineInterval.OneMinute, data =>
                    {
                        try {
                            MinuteLTC = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId12 = manualWebSocketClient12.ConnectToKlineWebSocket("LTCUSDT", KlineInterval.OneHour, data =>
                    {
                        try {
                            HourLTC = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId13 = manualWebSocketClient13.ConnectToKlineWebSocket("LTCUSDT", KlineInterval.OneDay, data =>
                    {
                        try {
                            DayLTC = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId26 = manualWebSocketClient26.ConnectToKlineWebSocket("LTCUSDT", KlineInterval.FiveMinutes, data =>
                    {
                        try {
                            FiveMinuteLTC = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId27 = manualWebSocketClient27.ConnectToKlineWebSocket("LTCUSDT", KlineInterval.FifteenMinutes, data =>
                    {
                        try {
                            FifteenMinuteLTC = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId28 = manualWebSocketClient28.ConnectToKlineWebSocket("LTCUSDT", KlineInterval.ThirtyMinutes, data =>
                    {
                        try
                        {
                            ThirtyMinuteLTC = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    ////////////////////////////////////////   XRP-USDT   ///////////////////////////////////////
                    var socketId16 = manualWebSocketClient16.ConnectToKlineWebSocket("XRPUSDT", KlineInterval.OneMinute, data =>
                    {
                        try {
                            MinuteXRP = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId17 = manualWebSocketClient17.ConnectToKlineWebSocket("XRPUSDT", KlineInterval.OneHour, data =>
                    {
                        try {
                            HourXRP = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId18 = manualWebSocketClient18.ConnectToKlineWebSocket("XRPUSDT", KlineInterval.OneDay, data =>
                    {
                        try {
                            DayXRP = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId29 = manualWebSocketClient29.ConnectToKlineWebSocket("XRPUSDT", KlineInterval.FiveMinutes, data =>
                    {
                        try {
                            FiveMinuteXRP = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId30 = manualWebSocketClient30.ConnectToKlineWebSocket("XRPUSDT", KlineInterval.FifteenMinutes, data =>
                    {
                        try {
                            FifteenMinuteXRP = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });

                    var socketId31 = manualWebSocketClient31.ConnectToKlineWebSocket("XRPUSDT", KlineInterval.ThirtyMinutes, data =>
                    {
                        try {
                            ThirtyMinuteXRP = data;
                        }
                        catch (Exception)
                        {
                            Environment.Exit(0);
                        }
                    });
                }
                catch (Exception ex)
                {
                    Console.WriteLine("ERROR ON SOCKET:  " + ex.Message);
                    Environment.Exit(0);
                }
            });

            WebSocketSyncing.Start();

            //////////////////////////////////////////////////////////////
            Thread SetWebSocketData = new Thread(() =>
            {
                while (true)
                {
                    if (Minute != null && FiveMinute != null && FifteenMinute != null && ThirtyMinute != null && Hour != null && Day != null &&
                        MinuteETH != null && FiveMinuteETH != null && FifteenMinuteETH != null && ThirtyMinuteETH != null && HourETH != null && DayETH != null &&
                        MinuteLTC != null && FiveMinuteLTC != null && FifteenMinuteLTC != null && ThirtyMinuteLTC != null && HourLTC != null && DayLTC != null &&
                        MinuteXRP != null && FiveMinuteXRP != null && FifteenMinuteXRP != null && ThirtyMinuteXRP != null && HourXRP != null && DayXRP != null)
                    {
                        using (var db = new ExchangeEntities())
                        {
                            var candlesList = db.CandlesDatas.ToList();
                            for (int t = 0; t < candlesList.Count; t++)
                            {
                                if (candlesList[t].Status.Value)
                                {
                                    var tmp = candlesList[t];
                                    var dt  = db.CandlesDatas.Where(x => x.SymbolName == tmp.SymbolName && x.TimeFrame == tmp.TimeFrame).FirstOrDefault();
                                    BinanceKlineData commonDt = null;
                                    try
                                    {
                                        if (dt != null)
                                        {
                                            if (dt.SymbolName == "BTC-USDT" && dt.TimeFrame == "OneMinute")
                                            {
                                                commonDt = Minute;
                                            }
                                            else if (dt.SymbolName == "BTC-USDT" && dt.TimeFrame == "FiveMinute")
                                            {
                                                commonDt = FiveMinute;
                                            }
                                            else if (dt.SymbolName == "BTC-USDT" && dt.TimeFrame == "FifteenMinute")
                                            {
                                                commonDt = FifteenMinute;
                                            }
                                            else if (dt.SymbolName == "BTC-USDT" && dt.TimeFrame == "ThirtyMinute")
                                            {
                                                commonDt = ThirtyMinute;
                                            }
                                            else if (dt.SymbolName == "BTC-USDT" && dt.TimeFrame == "OneHour")
                                            {
                                                commonDt = Hour;
                                            }
                                            else if (dt.SymbolName == "BTC-USDT" && dt.TimeFrame == "OneDay")
                                            {
                                                commonDt = Day;
                                            }
                                            else if (dt.SymbolName == "ETH-USDT" && dt.TimeFrame == "OneMinute")
                                            {
                                                commonDt = MinuteETH;
                                            }
                                            else if (dt.SymbolName == "ETH-USDT" && dt.TimeFrame == "FiveMinute")
                                            {
                                                commonDt = FiveMinuteETH;
                                            }
                                            else if (dt.SymbolName == "ETH-USDT" && dt.TimeFrame == "FifteenMinute")
                                            {
                                                commonDt = FifteenMinuteETH;
                                            }
                                            else if (dt.SymbolName == "ETH-USDT" && dt.TimeFrame == "ThirtyMinute")
                                            {
                                                commonDt = ThirtyMinuteETH;
                                            }
                                            else if (dt.SymbolName == "ETH-USDT" && dt.TimeFrame == "OneHour")
                                            {
                                                commonDt = HourETH;
                                            }
                                            else if (dt.SymbolName == "ETH-USDT" && dt.TimeFrame == "OneDay")
                                            {
                                                commonDt = DayETH;
                                            }
                                            else if (dt.SymbolName == "LTC-USDT" && dt.TimeFrame == "OneMinute")
                                            {
                                                commonDt = MinuteLTC;
                                            }
                                            else if (dt.SymbolName == "LTC-USDT" && dt.TimeFrame == "FiveMinute")
                                            {
                                                commonDt = FiveMinuteLTC;
                                            }
                                            else if (dt.SymbolName == "LTC-USDT" && dt.TimeFrame == "FifteenMinute")
                                            {
                                                commonDt = FifteenMinuteLTC;
                                            }
                                            else if (dt.SymbolName == "LTC-USDT" && dt.TimeFrame == "ThirtyMinute")
                                            {
                                                commonDt = ThirtyMinuteLTC;
                                            }
                                            else if (dt.SymbolName == "LTC-USDT" && dt.TimeFrame == "OneHour")
                                            {
                                                commonDt = HourLTC;
                                            }
                                            else if (dt.SymbolName == "LTC-USDT" && dt.TimeFrame == "OneDay")
                                            {
                                                commonDt = DayLTC;
                                            }
                                            else if (dt.SymbolName == "XRP-USDT" && dt.TimeFrame == "OneMinute")
                                            {
                                                commonDt = MinuteXRP;
                                            }
                                            else if (dt.SymbolName == "XRP-USDT" && dt.TimeFrame == "FiveMinute")
                                            {
                                                commonDt = FiveMinuteXRP;
                                            }
                                            else if (dt.SymbolName == "XRP-USDT" && dt.TimeFrame == "FifteenMinute")
                                            {
                                                commonDt = FifteenMinuteXRP;
                                            }
                                            else if (dt.SymbolName == "XRP-USDT" && dt.TimeFrame == "ThirtyMinute")
                                            {
                                                commonDt = ThirtyMinuteXRP;
                                            }
                                            else if (dt.SymbolName == "XRP-USDT" && dt.TimeFrame == "OneHour")
                                            {
                                                commonDt = HourXRP;
                                            }
                                            else if (dt.SymbolName == "XRP-USDT" && dt.TimeFrame == "OneDay")
                                            {
                                                commonDt = DayXRP;
                                            }

                                            DateTime javaEpoch = new DateTime(1970, 1, 1);

                                            dt.H         = commonDt.Kline.High;
                                            dt.L         = commonDt.Kline.Low;
                                            dt.O         = commonDt.Kline.Open;
                                            dt.C         = commonDt.Kline.Close;
                                            dt.Volume    = commonDt.Kline.Volume;
                                            dt.TimeStamp = (commonDt.Kline.StartTime.Ticks - javaEpoch.Ticks) / TimeSpan.TicksPerMillisecond;

                                            db.Configuration.ValidateOnSaveEnabled = false;
                                            db.SaveChanges();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("ERROR ON SAVING:  " + ex.Message);
                                    }
                                }
                            }
                        }
                        //Console.Clear();
                        //Console.WriteLine("      *** BTC-USDT Candle *** "); Console.WriteLine();
                        //Console.WriteLine("MINUTE:  " + "HIGH: " + Minute.Kline.High + "  LOW: " + Minute.Kline.Low + "  OPEN: " + Minute.Kline.Open + "  CLOSE: " + Minute.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("HOUR:    " + "HIGH: " + Hour.Kline.High + "  LOW: " + Hour.Kline.Low + "  OPEN: " + Hour.Kline.Open + "  CLOSE: " + Hour.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("DAY:     " + "HIGH: " + Day.Kline.High + "  LOW: " + Day.Kline.Low + "  OPEN: " + Day.Kline.Open + "  CLOSE: " + Day.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("WEEK:    " + "HIGH: " + Week.Kline.High + "  LOW: " + Week.Kline.Low + "  OPEN: " + Week.Kline.Open + "  CLOSE: " + Week.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("MONTH:   " + "HIGH: " + Month.Kline.High + "  LOW: " + Month.Kline.Low + "  OPEN: " + Month.Kline.Open + "  CLOSE: " + Month.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("      *** ETH-USDT Candle *** "); Console.WriteLine();
                        //Console.WriteLine("MINUTE:  " + "HIGH: " + MinuteETH.Kline.High + "  LOW: " + MinuteETH.Kline.Low + "  OPEN: " + MinuteETH.Kline.Open + "  CLOSE: " + MinuteETH.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("HOUR:    " + "HIGH: " + HourETH.Kline.High + "  LOW: " + HourETH.Kline.Low + "  OPEN: " + HourETH.Kline.Open + "  CLOSE: " + HourETH.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("DAY:     " + "HIGH: " + DayETH.Kline.High + "  LOW: " + DayETH.Kline.Low + "  OPEN: " + DayETH.Kline.Open + "  CLOSE: " + DayETH.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("WEEK:    " + "HIGH: " + WeekETH.Kline.High + "  LOW: " + WeekETH.Kline.Low + "  OPEN: " + WeekETH.Kline.Open + "  CLOSE: " + WeekETH.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("MONTH:   " + "HIGH: " + MonthETH.Kline.High + "  LOW: " + MonthETH.Kline.Low + "  OPEN: " + MonthETH.Kline.Open + "  CLOSE: " + MonthETH.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("      *** LTC-USDT Candle *** "); Console.WriteLine();
                        //Console.WriteLine("MINUTE:  " + "HIGH: " + MinuteLTC.Kline.High + "  LOW: " + MinuteLTC.Kline.Low + "  OPEN: " + MinuteLTC.Kline.Open + "  CLOSE: " + MinuteLTC.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("HOUR:    " + "HIGH: " + HourLTC.Kline.High + "  LOW: " + HourLTC.Kline.Low + "  OPEN: " + HourLTC.Kline.Open + "  CLOSE: " + HourLTC.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("DAY:     " + "HIGH: " + DayLTC.Kline.High + "  LOW: " + DayLTC.Kline.Low + "  OPEN: " + DayLTC.Kline.Open + "  CLOSE: " + DayLTC.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("WEEK:    " + "HIGH: " + WeekLTC.Kline.High + "  LOW: " + WeekLTC.Kline.Low + "  OPEN: " + WeekLTC.Kline.Open + "  CLOSE: " + WeekLTC.Kline.Close); Console.WriteLine();
                        //Console.WriteLine("MONTH:   " + "HIGH: " + MonthLTC.Kline.High + "  LOW: " + MonthLTC.Kline.Low + "  OPEN: " + MonthLTC.Kline.Open + "  CLOSE: " + MonthLTC.Kline.Close); Console.WriteLine();
                        Thread.Sleep(900);
                    }
                }
            });

            SetWebSocketData.Start();
        }
Beispiel #8
0
 private static void Monitor(InstanceBinanceWebSocketClient ws, string symbol) => ws.ConnectToTradesWebSocket(symbol, MessageEventDispatcher);
        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();
        }
Beispiel #10
0
        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&timestamp=1499827319559";
             * string timestamp = GetTimestamp();
             * string str = "symbol=TRXETH&side=SELL&type=LIMIT&timeInForce=GTC&quantity=200&price=0.00011470&recvWindow=10000000&timestamp=" + 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&timestamp=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();
        }
Beispiel #11
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();
        }