示例#1
0
        private static decimal GetHeldCoins(BinanceClient client, string currency)
        {
            string trimmedName = currency.ToUpper().Replace("ETH", "");

            try
            {
                Binance.API.Csharp.Client.Models.Market.Balance balance = client.GetAccountInfo().Result.Balances.Where(p => p.Asset == trimmedName.ToUpper()).FirstOrDefault();
                return(decimal.Truncate(balance.Free));
            }
            catch
            {
                return(-1);
            }
        }
示例#2
0
        public static void GetExistingHoldings(BinanceClient client, string baseCurrency)
        {
            //Get the currencies that we have ordered in the past
            foreach (Binance.API.Csharp.Client.Models.Market.Balance b in client.GetAccountInfo().Result.Balances.Where(p => p.Free > 0))
            {
                try
                {
                    var allOrders = client.GetTradeList(b.Asset + baseCurrency);
                    if (allOrders.Result != null)
                    {
                        foreach (var trade in allOrders.Result)
                        {
                            BinanceAPIMain.AllCurrencies.Where(p => p.Name == b.Asset + baseCurrency).FirstOrDefault().HeldPositions.Add(trade.Quantity, trade.Price);
                        }
                        BinanceAPIMain.AllCurrencies.Where(p => p.Name == b.Asset + baseCurrency).FirstOrDefault().CalculateReturn(BinanceAPIMain.AllCurrencies);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }
            var heldCurrencies = BinanceAPIMain.AllCurrencies.Where(x => x.HeldPositions.Count > 0);

            //Now output the data to a text file.
            using (StreamWriter wr = new StreamWriter(@"C:\Users\user\Desktop\HeldPositions.csv", true))
            {
                wr.WriteLine("Symbol, Purchase Value, Current Value, Purchase Value USD, Current Value USD, RoR");
                foreach (Currency c in heldCurrencies)
                {
                    wr.WriteLine(
                        c.Name + "," +
                        c.PurchaseValue.ToString() + "," +
                        c.CurrentValue.ToString() + "," +
                        c.PurchaseValueUSD.ToString() + "," +
                        c.CurrentValueUSD.ToString() + "," +
                        c.Return.ToString());
                }
            }
        }
示例#3
0
        public static string GetCurrentPurchases(BinanceClient client)
        {
            var currentCurrencies = BinanceAPIMain.AllCurrencies.Where(p => p.InTrade);
            var currentPrices     = client.GetAllPrices().Result;

            StringBuilder b = new StringBuilder();

            b.AppendLine("Current gain/loss:");

            foreach (Currency c in currentCurrencies)
            {
                var     purchasePrice = c.CoinsBought.FirstOrDefault().Item2;
                var     currentPrice  = currentPrices.Where(p => p.Symbol.ToLower() == c.Name.ToLower()).Select(p => p.Price).FirstOrDefault();
                decimal percentage    = Math.Round(((currentPrice - purchasePrice) / purchasePrice) * 100, 2);
                b.AppendLine(c.Name + ":");
                b.AppendLine("\tBought at: " + purchasePrice);
                b.AppendLine("\tCurrent Price: " + currentPrice);
                b.AppendLine("\tPercent Change:" + percentage.ToString());
                b.AppendLine();
            }

            return(b.ToString());
        }
示例#4
0
        public static void ExecuteTrade(BinanceClient client, KlineData data, Currency currency, OrderSide side)
        {
            var allPrices = client.GetAllPrices().Result;
            var price     = allPrices.Where(p => p.Symbol.Contains(currency.Name)).Select(a => a.Price).FirstOrDefault();

            DateTime currentTime = DateTime.Now;

            if (side == OrderSide.BUY && BinanceAPIMain.TotalTrades < 4)
            {
                //Before we execute, update the allotted coins
                BinanceAPIMain.CalculateCoinsToTrade(client, currency, allPrices);

                //Orders will break if not successful, so check for try/catch block and add into currency ledger or move on.
                try
                {
                    var order = client.PostNewOrder(currency.Name.ToLower(), currency.AllottedCoins, 0.1m, side, OrderType.MARKET, TimeInForce.IOC);
                    Task.WaitAll(order);
                    if (order.Result.OrderId != -1)
                    {
                        BinanceAPIMain.TotalTrades++;
                        currency.InTrade = true;
                        var finalCoinsBought = GetHeldCoins(client, currency.Name);
                        currency.CoinsBought.Add(new Tuple <decimal, decimal>(finalCoinsBought, price));
                        BinanceAPIMain.WriteToLog(finalCoinsBought + ":" + currency.Name + ": go in on trade at: " + price + " Time: " + currentTime, ConsoleColor.Yellow);
                        BinanceAPIMain.WriteToLogTrades(currency.Name + ": Buy " + finalCoinsBought + " coins at " + price + " Time: " + currentTime);
                        BinanceAPIMain.WriteToCurrencyFile(finalCoinsBought + "|" + price, currency.Name);
                    }
                }
                catch (OperationCanceledException oce)
                {
                    BinanceAPIMain.WriteToLog(oce.Message + " while buying " + currency.Name + " " + DateTime.Now, ConsoleColor.DarkRed);
                }
                catch (Exception ex)
                {
                    BinanceAPIMain.WriteToLog(ex.InnerException + " while buying " + currency.Name + " " + DateTime.Now, ConsoleColor.DarkRed);
                }
            }
            else if (side == OrderSide.SELL)
            {
                try
                {
                    foreach (Tuple <decimal, decimal> tuplePair in currency.CoinsBought)
                    {
                        var order = client.PostNewOrder(currency.Name.ToLower(), tuplePair.Item1, 0.1m, side, OrderType.MARKET, TimeInForce.IOC);
                        Task.WaitAll(order);
                        if (order.Result.OrderId != -1)
                        {
                            decimal      percentage = Math.Round(((price - tuplePair.Item2) / tuplePair.Item2) * 100, 2);
                            ConsoleColor color      = percentage > 0 ? ConsoleColor.White : ConsoleColor.Red;

                            BinanceAPIMain.WriteToLogTrades(currency.Name + ": Sell " + tuplePair.Item1 + " coins at " + price + " Time: " + currentTime +
                                                            " for a " + percentage + " percent change");
                            BinanceAPIMain.WriteToLog(currency.Name + ": sold " + tuplePair.Item1 + " coins at " + price + " on " + currentTime + Environment.NewLine +
                                                      currency.Name + ": Made: " + (price - tuplePair.Item2) + " Percentage: " + percentage, color);
                        }
                    }
                    BinanceAPIMain.TotalTrades--;
                    currency.CoinsBought.Clear();
                    currency.LastSalePrice       = data.Close;
                    currency.LastTransactionTime = DateTime.Now;

                    //Remove the file which indicated we had an open position on the trade.
                    if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\BinanceAPI\" + currency.Name + ".txt"))
                    {
                        File.Delete(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\BinanceAPI\" + currency.Name + ".txt");
                    }
                }
                catch (OperationCanceledException oce)
                {
                    BinanceAPIMain.WriteToLog(oce.Message + " while selling " + currency.Name + " " + DateTime.Now, ConsoleColor.DarkRed);
                }
                catch (Exception ex)
                {
                    BinanceAPIMain.WriteToLog(ex.InnerException + " while selling " + currency.Name + " " + DateTime.Now, ConsoleColor.DarkRed);
                }
            }
        }
示例#5
0
        static void Main(string[] args)
        {
            var binanceClient  = new BinanceAPI.BinanceClient();
            var binanceService = new BinanceService(binanceClient);

            //GET TICKER DEPTH
            var getDepth = binanceService.GetDepthAsync("BNBBTC");

            Task.WaitAll(getDepth);
            dynamic depth = getDepth.Result;

            Console.WriteLine(depth);

            //GET ACCOUNT INFORMATION
            var getAccount = binanceService.GetAccountAsync();

            Task.WaitAll(getAccount);
            dynamic account = getAccount.Result;

            Console.WriteLine(account);

            //GET ORDERS FOR SYMBOL
            var getOrders = binanceService.GetOrdersAsync("BNBBTC", 100);

            Task.WaitAll(getOrders);
            dynamic orders = getOrders.Result;

            Console.WriteLine(orders);

            //GET MY TRADES
            var getMyTrades = binanceService.GetTradesAsync("WTCBTC");

            Task.WaitAll(getAccount);
            dynamic trades = getMyTrades.Result;

            Console.WriteLine(trades);

            //GET ALL PRICES
            List <Prices> prices = new List <Prices>();

            prices = binanceService.ListPrices();
            Console.WriteLine(prices);

            //GET PRICE OF SYMBOL
            double symbol = binanceService.GetPriceOfSymbol("BNBBTC");

            Console.WriteLine("Price of BNB: " + symbol);

            //PLACE BUY ORDER
            var placeBuyOrder = binanceService.PlaceBuyOrderAsync("NEOBTC", 1.00, 00.008851);

            Task.WaitAll(placeBuyOrder);
            dynamic buyOrderResult = placeBuyOrder.Result;

            Console.WriteLine(buyOrderResult);

            //PLACE SELL ORDER
            var placeSellOrder = binanceService.PlaceSellOrderAsync("NEOBTC", 1.00, 00.008851);

            Task.WaitAll(placeSellOrder);
            dynamic sellOrderResult = placeSellOrder.Result;

            Console.WriteLine(sellOrderResult);

            //TEST ORDER---------------------------------------------------------------------------
            var placeOrderTest = binanceService.PlaceTestOrderAsync("NEOBTC", "SELL", 1.00, 00.006151);

            Task.WaitAll(placeOrderTest);
            dynamic testOrderResult = placeOrderTest.Result;

            Console.WriteLine(testOrderResult);
            //-------------------------------------------------------------------------------------

            //CHECK ORDER STATUS BY ID
            var checkOrder = binanceService.CheckOrderStatusAsync("NEOBTC", 5436663);

            Task.WaitAll(checkOrder);
            dynamic checkOrderResult = checkOrder.Result;

            Console.WriteLine(checkOrderResult);

            //DELETE ORDER BY ID
            var deleteOrder = binanceService.CancelOrderAsync("NEOBTC", 5436663);

            Task.WaitAll(deleteOrder);
            dynamic deleteOrderResult = deleteOrder.Result;

            Console.WriteLine(deleteOrderResult);
        }
示例#6
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);
            }
        }
示例#7
0
        public static void CalculateTradeAlgorithm(this Currency currency, KlineData data, BinanceClient client)
        {
            DateTime currentTime = UnixTimeStampToDateTime(data.StartTime);
            DateTime endTime     = UnixTimeStampToDateTime(data.EndTime);

            try
            {
                if (currency.CloseTime == data.EndTime)
                {
                    return;
                }

                currency.CloseTime = data.EndTime;
                //Get the last 99 klines to calc
                var sticks = client.GetCandleSticks(currency.Name, BinanceAPIMain.Interval, null, currentTime, 99).Result;

                var sticks1hr = client.GetCandleSticks(currency.Name, TimeInterval.Hours_1, null, currentTime, 200).Result;

                //Perhaps we calculate the EMA with the latest price, but the previous EMA is the close of the last kline?
                if (currency.PreviousRSI != -1)
                {
                    currency.PreviousRSI = currency.RSI.Last();
                }
                currency.EMA12.Clear();
                currency.EMA7.Clear();
                currency.EMA26.Clear();
                currency.EMA99.Clear();
                currency.MACD.Clear();
                currency.Signal.Clear();
                currency.MACDHistogram.Clear();
                currency.RSI.Clear();
                currency.EMA12                 = CalculateEMA(sticks, 12);
                currency.EMA26                 = CalculateEMA(sticks, 26);
                currency.EMA99                 = CalculateEMA(sticks, 99);
                currency.EMA7                  = CalculateEMA(sticks, 7);
                currency.MACD                  = SubtractValues(currency.EMA12, currency.EMA26);
                currency.Signal                = CalculateTrendLine(currency.MACD, 9);
                currency.MACDHistogram         = SubtractValues(currency.MACD, currency.Signal);
                currency.MACDHistPosPercentage = CalcLowestPercentPos(currency.MACDHistogram, 10);
                currency.RSI = CalculateRSI(sticks, 21);

                if (currency.PreviousRSI == -1)
                {
                    currency.PreviousRSI = currency.RSI.Last();
                }

                ConsoleColor color = currency.MACDHistogram.Last() < 0 ? ConsoleColor.Magenta : ConsoleColor.Cyan;
                BinanceAPIMain.WriteToLog("Symbol " + currency.Name + " Price: " + data.Close + " Close Time:" + endTime + Environment.NewLine +
                                          "MACD Histogram: " + currency.MACDHistogram.Last() + Environment.NewLine +
                                          "MACD Histogram Lowest 10%: " + currency.MACDHistPosPercentage + Environment.NewLine +
                                          "RSI: " + currency.RSI.Last() + Environment.NewLine +
                                          "RSI-1: " + currency.PreviousRSI + Environment.NewLine +
                                          "Signal: " + currency.Signal.Last() + Environment.NewLine +
                                          "EMA99(n): " + Decimal.Round(currency.EMA99.Last(), 7) + " EMA99(n-1): " + Decimal.Round(currency.EMA99[currency.EMA7.Count - 2], 7) + Environment.NewLine +
                                          "EMA7(n): " + Decimal.Round(currency.EMA7.Last(), 7) + " EMA7(n-1): " + Decimal.Round(currency.EMA7[currency.EMA7.Count - 2], 7) +
                                          " EMA7(n-2): " + Decimal.Round(currency.EMA7[currency.EMA7.Count - 3], 7) + Environment.NewLine, color, createFile: false);


                if (!currency.InTrade && currency.MACDHistogram != null && currency.CycleSeen &&
                    currency.MACDHistogram.Last() > currency.MACDHistPosPercentage &&
                    currency.EMA7.Last() > (currency.EMA7[currency.EMA7.Count - 2] * (decimal)1.0005) &&
                    currency.EMA7[currency.EMA7.Count - 2] > currency.EMA7[currency.EMA7.Count - 3] &&
                    currency.EMA99.Last() > currency.EMA99[currency.EMA99.Count() - 2] &&
                    currency.RSI.Last() < 60)
                {
                    if (BinanceAPIMain.Debug == "false")
                    {
                        Trading.ExecuteTrade(client, data, currency, OrderSide.BUY);
                    }
                    else
                    {
                        Trading.ExecuteTradeDebug(client, data, currency, OrderSide.BUY);
                    }
                }
                else if (currency.InTrade &&
                         (currency.RSI.Last() >= 70 || currency.RSI[currency.RSI.Count() - 2] >= 70) && currency.RSI.Last() < currency.RSI[currency.RSI.Count() - 2] &&
                         data.Close > currency.CoinsBought.Min(p => p.Item2))
                {
                    if (BinanceAPIMain.Debug == "false")
                    {
                        Trading.ExecuteTrade(client, data, currency, OrderSide.SELL);
                    }
                    else
                    {
                        Trading.ExecuteTradeDebug(client, data, currency, OrderSide.SELL);
                    }
                    currency.InTrade   = false;
                    currency.CycleSeen = false;
                }
                else if (!currency.CycleSeen && currency.MACDHistogram.Last() < 0 && currency.MACDHistogram != null)
                {
                    currency.CycleSeen           = true;
                    currency.LastTransactionTime = DateTime.Now.AddMinutes(-2);
                    BinanceAPIMain.WriteToLog("Symbol: " + currency.Name + " Cycle Seen: " + currency.CycleSeen.ToString() + Environment.NewLine, ConsoleColor.Cyan);
                }
            }
            catch (Exception ex)
            {
                BinanceAPIMain.WriteToLog(currency.Name + ": " + ex.Message + ex.StackTrace + " from currency.CalcAlgorithm" + " at " + DateTime.Now, ConsoleColor.DarkRed);
            }
        }