public static async void WriteToLog(string message, ConsoleColor color, bool createFile = true)
        {
            try
            {
                Console.ForegroundColor = color;

                if (color == ConsoleColor.DarkRed)
                {
                    TelegramBot.SendBotMessage(message, ConfigurationManager.AppSettings["EMail"]);
                }
                Console.WriteLine(message);
                Console.ResetColor();

                ///Colors:
                ///White - Sold at profit
                ///Red - Sold at loss
                ///Cyan - information
                ///Magenta - possibly falling in price
                ///Green - threading issue falling back to standard format

                if (createFile == true)
                {
                    string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"BinanceAPI\TradeAlgorithm.txt";
                    using (StreamWriter wr = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\BinanceAPI\TradeAlgorithm.txt", true))
                    {
                        await wr.WriteLineAsync(message + Environment.NewLine);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        public static async void WriteToLogTrades(string message)
        {
            try
            {
                using (StreamWriter wr = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\BinanceAPI\TradeAlgorithm_Trades.txt", true))
                {
                    await wr.WriteLineAsync(message + Environment.NewLine);
                }

                TelegramBot.SendBotMessage(message, ConfigurationManager.AppSettings["EMail"]);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        static void Main(string[] args)
        {
            try
            {
                Console.Title = "BinanceAPI 1.2.5";
                //Setup the telegram bot
                Bot.OnMessage += TelegramBot.BotOnMessageReceived;
                var me = Bot.GetMeAsync().Result;
                Bot.StartReceiving();
                Console.WriteLine($"Start listening for @{me.Username}");

                //Check and see if we have any open currencies due to system crash.
                //If not, then use the configuration setting file to allocate proper coins by total value and % allocation.
                GetAllCoins(BinanceClient);

                if (Debug == "false")
                {
                    //Get Streaming data from websocket and attempt to place trades on "turtle" technique
                    ConsoleKeyInfo cki;
                    do
                    {
                        Console.WriteLine();
                        Console.WriteLine("Press (Q) to quit");
                        TelegramBot.SendBotMessage("Binance API Startup at " + DateTime.Now.ToString(), ConfigurationManager.AppSettings["EMail"]);
                        RunBinanceConnection().GetAwaiter().GetResult();
                        cki = Console.ReadKey();
                    }while (cki.Key != ConsoleKey.Q);
                    //Once we get ready to close the app, sell all coins that havent traded yet.
                    //Trading.SellAllHoldings(AllCurrencies, BinanceClient);
                }
                else if (Debug == "true")
                {
                    //Get the last 500 historical klines and feed them one by one into the same algorithm.
                    MimicStreamingData(BinanceClient);
                }
                Bot.StopReceiving();
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message + ex.InnerException, ConsoleColor.DarkRed);
                Console.WriteLine(ex.Message + ex.InnerException);
            }
        }
Esempio n. 4
0
        static void GetStreamingData(BinanceClient client, ApiClient apiClient, TimeInterval interval)
        {
            try
            {
                mres = new ManualResetEventSlim();
                Console.WriteLine("Type QUIT and enter to exit.");
                TelegramBot.SendBotMessage("Binance API Startup at " + DateTime.Now.ToString(), ConfigurationManager.AppSettings["EMail"]);
restart:
                do
                {
                    cts = new CancellationTokenSource();

                    List <Task> tasks = new List <Task>
                    {
                        Task.Factory.StartNew(ListenForQuit)
                    };
                    foreach (var symbol in BinanceAPIMain.AllCurrencies.Select(p => p.Name).ToList())
                    {
                        var task = new Task(() => client.ListenKlineEndpoint(symbol.ToLower(), interval, (data) =>
                        {
                            KlineHandler(data, symbol, client);
                        }, cts));

                        tasks.Add(task);
                        task.Start();
                    }

                    while (tasks.TrueForAll(p =>
                                            p.Status == TaskStatus.Canceled ||
                                            p.Status == TaskStatus.Faulted ||
                                            p.Status == TaskStatus.RanToCompletion ||
                                            p.Status == TaskStatus.WaitingForActivation ||
                                            p.Status == TaskStatus.WaitingForChildrenToComplete ||
                                            p.Status == TaskStatus.WaitingToRun
                                            ))
                    {
                        Thread.Sleep(50);
                    }

                    cts.CancelAfter(TimeSpan.FromSeconds(84600));

                    // Need to end ListenForQuit method...
                    cts.Token.Register(() =>
                    {
                        while (!mres.IsSet)
                        {
                            IntPtr handle = GetConsoleWindow();
                            ShowWindow(handle, SW_SHOW);
                            SetForegroundWindow(handle);
                            SendKeys.SendWait("`");
                            Thread.Sleep(100);
                        }
                        mres.Reset();
                    });

                    Task.WaitAll(tasks.ToArray());

                    // Wait for socket closure... but don't get spammy.
                    int openSockets = apiClient._openSockets.Count;
                    Console.WriteLine($"Waiting for {apiClient._openSockets.Count} web socket closure...");
                    while (apiClient._openSockets.Count > 0)
                    {
                        if (openSockets != apiClient._openSockets.Count)
                        {
                            openSockets = apiClient._openSockets.Count;
                            Console.WriteLine($"Waiting for {apiClient._openSockets.Count} web socket closure...");
                        }
                        Thread.Sleep(3000);
                    }

                    cts.Dispose();
                    Array.ForEach(tasks.ToArray(), p => p.Dispose());
                }while (restart);

                ConsoleKeyInfo cki;
                do
                {
                    Console.WriteLine("Gracefully stopped executing.");
                    Console.WriteLine();
                    Console.WriteLine("Press (R) to restart or (Q) to quit");
                    cki = Console.ReadKey();
                }while (cki.Key != ConsoleKey.R && cki.Key != ConsoleKey.Q);

                if (cki.Key == ConsoleKey.R)
                {
                    Console.WriteLine();
                    Console.WriteLine("Restarting...");
                    Console.WriteLine();
                    restart = true;
                    goto restart;
                }

                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }