Example #1
0
        public Trade_package(decimal _precent, string _currency, SymbolsDate _buySymbolsDate, SymbolsDate _sellSymbolsDate)
        {
            api             = StaticVariables.api;
            itsBuyArbitrage = true;

            percent         = _precent;
            buySymbolsDate  = _buySymbolsDate;
            sellSymbolsDate = _sellSymbolsDate;
            currency        = _currency;

            buySymbol  = buySymbolsDate.symbole;
            sellSymbol = sellSymbolsDate.symbole;

            minAmountTrade = Math.Max(buySymbolsDate.MinAmount, sellSymbolsDate.MinAmount);
            maxAmountTrade = WalletFunc.GetMaxAmountTrade(buySymbolsDate.orderTrade.request.Price, buySymbolsDate.payment);
            maxAmountTrade = StaticVariables.api.ClampOrderQuantity(buySymbol, maxAmountTrade);
            if (maxAmountTrade < minAmountTrade)
            {
                string warningMessage = String.Format("currency - {0}, buySymbol - {1}, buy.MinAmount - {2}, sellSymbols - {3}, sell.MinAmount- {4}, minAmountTrade - {5}, maxAmountTrade - {6}", currency, buySymbol, buySymbolsDate.MinAmount, sellSymbol, sellSymbolsDate.MinAmount, minAmountTrade, maxAmountTrade);
                PrintTable.PrintConsole(warningMessage);
                PrintFunc.AddLine(StaticVariables.pathWithDate + "WARNING_maxAmount.txt", warningMessage);

                maxAmountTrade = minAmountTrade;
            }
        }
Example #2
0
        // TODO Add Func TradeFast
        //// call by Start.FindAndTrade
        //public bool StartTradePackageFaster()
        //{
        //    StartTradePackage();
        //    revnuCalculation(percent);
        //    return result;
        //}

        // call by this.StartTradePackageMagic or this.StartTradePackageFaster
        public void StartTradePackage()
        {
            FindArbitrageSymbol();
            Amounts();
            SetArbitrageSymbolsDate();
            walletResult = WalletFunc.WalletResult(StaticVariables.WalletAvailableAmount);    // -start
        }
Example #3
0
        public SymbolsDate(string _symbole, ExchangeTicker ticker, MagicNumber _magicNumber)
        {
            Symbole   = _symbole;
            lastPrice = ticker.Last;
            valume    = WalletFunc.ConversionPrice((ticker.Volume.PriceAmount * lastPrice), payment);

            if (StaticVariables.roundingPrice)
            {
                currencyRound = StaticVariables.api.GetRoundAmount(symbole, lastPrice);
            }

            MinAmount   = lastPrice;
            magicNumber = _magicNumber;
        }
Example #4
0
        public string PrintResult()
        {
            string res = String.Format("\nTime: {4},\toriginal Percentage: {8:P3},\tEnd Percentage: {2:P3} " +
                                       "\nusdTrade - {18},\tusdRevnuCalculation - {21}  usdRevnu - {19:N3}," +
                                       "\nAmount Trade: {0:N3},\tbtcTrade - {17},\tbtcRevnu - {20}," +
                                       "\nprice To Buy = {1},\tprice To Sell = {5},\trevnue: {3:P3}," +
                                       "\npercent - {8:P3}   percentPotential - {9:P3}   percent_real - {10:P3}   percent_beforeBuy - {11:P3}   " +
                                       "\npercent_beforeSell - {12:P3}   percent_beforeArbitrage - {13:P3}  percentTrade - {22:P3}    percent_End - {14:P3}" +
                                       "\nbuy-{15} & sell-{16},\ttrade case-{6},\tSuccess- {7},",
                                       AmountTrade,
                                       WalletFunc.ConversionPrice(Buy.request.Price, buySymbolsDate.payment),
                                       percent_end / 100,
                                       StaticVariables.revnuTrade / 100,
                                       buy.startTimeOrder,
                                       WalletFunc.ConversionPrice(Sell.request.Price, sellSymbolsDate.payment),
                                       (itsTradeFaster ? "Faster" : "Magic"),
                                       (succsseTrade ? "YES" : "NO"),
                                       percent / 100,
                                       percentPotential / 100,
                                       percent_0 / 100,
                                       percent_1 / 100,
                                       percent_2 / 100,
                                       percent_3 / 100,
                                       percent_end / 100,
                                       buySymbol,
                                       sellSymbol,
                                       btcTrade,
                                       usdTrade,
                                       usdRevnu,
                                       btcRevnu,
                                       usdRevnuCalculation,
                                       percentTrade
                                       );

            if (!succsseTrade)
            {
                res += String.Format("\nbuy - {0:P2},    sell - {1:P2},   arbitrage - {2:P2},",
                                     (buy.amountFilled / AmountTrade),
                                     (sell.amountFilled / AmountTrade),
                                     (arbitrage.amountFilled / arbitrage.Result.Amount));
            }

            return(res);
        }
        public static void FindAndTrade(bool trade)
        {
            StaticVariables.Wallet = WalletFunc.GetWallet();
#if DEBUG
            PrintDataDebug();
#endif

            DateTime currentTime;
            string   timeHouer;
            string   pathSummaryFind;
            int      numFind = 0;

            while (true)
            {
                numFind++;
                currentTime = DateTime.Now;
                List <OrderHandling> packageList = new List <OrderHandling>();

                int  i = 0;
                bool tradeSuccses;
                List <MagicNumber> magicNumbersToUpdate = new List <MagicNumber>();
                foreach (var item in StaticVariables.symbolsDateList)
                {
                    if (i % 5 == 0)
                    {
                        WalletFunc.ConversionPayment();
                    }
                    i++;

                    tradeSuccses = false;
                    do
                    {
                        OrderHandling package;
                        try
                        {
                            package = FindingSymbolsTrading.ArbitragePercent(item.Key, item.Value);
                        }
                        catch (Exception ex)
                        {
                            package = null;
                            DateTime localDate   = DateTime.Now;
                            string   printResult = String.Format("{0}\n{1}", localDate.ToString(), ex.ToString());
                            printResult += String.Format("\ncurrency - {0}", item.Key);
                            PrintException.Start(MethodBase.GetCurrentMethod().Name, printResult);
                        }

                        if (package != null)
                        {
                            packageList.Add(package);
                            PrintTable.Start(StaticVariables.pathFindFile + item.Key + ".csv", package.ToString(), "Trade_package");

                            // TODO Add Func TradeFast

                            List <MagicNumber> magicNumbersTradeMagicToUpdate = new List <MagicNumber>();
                            if (package.percentPotential > StaticVariables.revnuTrade)
                            {
                                if (StaticVariables.rateGateLimit)
                                {
                                    StaticVariables.api.RateLimit.OneOpportunity = true;
                                }

                                try
                                {
                                    if (package.StartTradePackageMagic())
                                    {
                                        tradeSuccses = TradeMagic.Start(package);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    StaticVariables.Wallet = WalletFunc.GetWallet();  // Wallet update. Because part of the trade was carried out. Apparently the amounts of coins have changed

                                    DateTime localDate   = DateTime.Now;
                                    string   printResult = String.Format("{0}\n{1}", localDate.ToString(), ex.ToString());
                                    PrintException.Start(MethodBase.GetCurrentMethod().Name, printResult);
                                    try
                                    {
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_" + item.Key + ".csv", package.Buy.ToString(), "OrderTrade");
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_" + item.Key + ".csv", package.Sell.ToString(), "OrderTrade");
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_" + item.Key + ".csv", package.Arbitrage.ToString(), "OrderTrade");
                                    }
                                    catch (Exception)
                                    {
                                        PrintTable.Start(StaticVariables.pathWithDate + "Exception_TradeMagic_Exception_" + item.Key + ".csv", package.ToString(), "Trade_package");
                                    }
                                }

                                if (StaticVariables.rateGateLimit)
                                {
                                    StaticVariables.api.RateLimit.OneOpportunity = false;
                                }

                                magicNumbersTradeMagicToUpdate.Add(package.buySymbolsDate.magicNumber);
                                magicNumbersTradeMagicToUpdate.Add(package.sellSymbolsDate.magicNumber);
                                magicNumbersTradeMagicToUpdate.Add(package.arbitrageSymbolsDate.magicNumber);
                                SqlMagicNumber.UpdateAll(magicNumbersTradeMagicToUpdate);
                            }
                            else
                            {
                                magicNumbersToUpdate.Add(package.buySymbolsDate.magicNumber);
                            }
                        }
                    } while (tradeSuccses);
                }

                SqlMagicNumber.UpdateAll(magicNumbersToUpdate);
                WaitingTimeML.Start();      // USE to ML_4
                timeHouer = String.Format("{0}-{1}-{2}", currentTime.Hour, currentTime.Minute, currentTime.Second);
                PrintTable.PrintConsole(timeHouer + "\t" + numFind);
                pathSummaryFind = StaticVariables.pathSummaryFind + "SummaryFind_" + timeHouer + ".csv";
                foreach (var item in packageList)
                {
                    PrintTable.Start(pathSummaryFind, item.ToString(), "Trade_package");
                    if (item.percent > StaticVariables.revnuTrade || item.percentPotential > StaticVariables.revnuTrade)
                    {
                        PrintTable.PrintConsole(item.ToConsole());
                        PrintTable.Start(StaticVariables.pathWithDate + "SummaryFind" + ".csv", item.ToString(), "Trade_package");
                    }
                }

#if DEBUG
                PrintFunc.PrintDictionary(StaticVariables.magicNumberList, nameof(StaticVariables.magicNumberList), StaticVariables.pathDataDebug);
#endif
            }
        }
Example #6
0
        public void WalletResultEnd()
        {
            succsseTrade = (buy.succsseTrade & sell.succsseTrade & arbitrage.succsseTrade);

            oldWalletAvailableAmount = new Dictionary <string, decimal>();
            foreach (var item in StaticVariables.WalletAvailableAmount)
            {
                oldWalletAvailableAmount.Add(item.Key, item.Value);
            }
            StaticVariables.Wallet   = WalletFunc.GetWallet();
            newWalletAvailableAmount = new Dictionary <string, decimal>();
            newWalletAvailableAmount = StaticVariables.WalletAvailableAmount;
            walletResult            += WalletFunc.WalletResult(newWalletAvailableAmount); // -after

            summaryTradeReal = String.Format("{0},,", succsseTrade);
            walletResultReal = walletResult + WalletFunc.WalletResultCompare(oldWalletAvailableAmount, newWalletAvailableAmount, out decimal sumStart, out decimal sumAfter, out decimal sumRevnu);   // -dif

            btcRevnu     = sumRevnu;
            usdRevnu     = WalletFunc.ConversionPrice(btcRevnu, StaticVariables.paymentWeighted, StaticVariables.usdName, StaticVariables.usdName);
            btcTrade     = WalletFunc.ConversionPrice(Expense, buySymbolsDate.payment);
            usdTrade     = Math.Round(WalletFunc.ConversionPrice(btcTrade, StaticVariables.paymentWeighted, StaticVariables.usdName, StaticVariables.usdName), 3);
            percentTrade = btcRevnu / btcTrade;


#if DEBUG
            bool DifferentCalculation = percentTrade == percent_end;
            summaryTradeReal += String.Format("{0},{1},,", DifferentCalculation, percent_end);
#endif

            summaryTradeReal += String.Format("{0},{1},{2},{3},{4},{5},,{6},{7},,{8}", buySymbol, usdRevnu, btcRevnu, percentTrade, usdTrade, btcTrade, sumStart, sumAfter, walletResultReal);

            if (!buy.succsseTrade)
            {
                newWalletAvailableAmount[buySymbolsDate.payment] -= (buy.Result.Amount - buy.Result.AmountFilled) * buy.request.Price;
                numFee++;
            }


            if (!sell.succsseTrade)
            {
                newWalletAvailableAmount[sellSymbolsDate.payment] += (sell.Result.Amount - sell.Result.AmountFilled) * sell.request.Price;
                numFee++;
            }

            if (!arbitrage.succsseTrade)
            {
                if (itsBuyArbitrage)
                {
                    newWalletAvailableAmount[arbitrageSymbolsDate.currency] += (arbitrage.Result.Amount - arbitrage.Result.AmountFilled) * arbitrage.request.Price;
                }
                else
                {
                    newWalletAvailableAmount[arbitrageSymbolsDate.payment] += (arbitrage.Result.Amount - arbitrage.Result.AmountFilled) * arbitrage.request.Price;
                }

                numFee++;
            }

            walletResult += WalletFunc.WalletResult(newWalletAvailableAmount);                                                                            // -addOrderLeft

            walletResult += WalletFunc.WalletResultCompare(oldWalletAvailableAmount, newWalletAvailableAmount, out sumStart, out sumAfter, out sumRevnu); // -dif

            btcRevnu            = sumRevnu;
            usdRevnu            = WalletFunc.ConversionPrice(btcRevnu, StaticVariables.paymentWeighted, StaticVariables.usdName, StaticVariables.usdName);
            btcTrade            = WalletFunc.ConversionPrice(Expense, buySymbolsDate.payment);
            usdTrade            = Math.Round(WalletFunc.ConversionPrice(btcTrade, StaticVariables.paymentWeighted, StaticVariables.usdName, StaticVariables.usdName), 3);
            percentTrade        = (btcRevnu / btcTrade) + (StaticVariables.FeeTrade * numFee);
            usdRevnuCalculation = Math.Round(usdTrade * ((percent_end / 100) - (StaticVariables.FeeTrade * 3)), 3);


#if DEBUG
            DifferentCalculation = percentTrade == percent_end;
            summaryTrade         = String.Format("{0},{1},{2},,", DifferentCalculation, percent_end, percentTrade);
#endif

            summaryTrade += String.Format("{0},{1},{2},{3},{4},{5},,{6},{7},,{8}", buySymbol, usdRevnu, btcRevnu, percentTrade, usdTrade, btcTrade, sumStart, sumAfter, walletResult);
        }
        public static bool HandlingOneOrderTrade(OrderHandling orderHandling, bool firstOrder)
        {
            orderHandling.OrderToCare.StartTrade();
            orderHandling.OrderToCare.Result = TradeUseCase.Order(orderHandling.OrderToCare.Request);
            string resPrint = String.Format("Handling Order - {0}-{1}, ExtraPercent {2:P0}, Percentage(without ExtraPercent) - {3:P3}, realPercentage - {4:P3}", (orderHandling.OrderToCare.request.IsBuy ? "Buy" :"Sell"), orderHandling.OrderToCare.request.Symbol, orderHandling.OrderToCare.extraPercent.Percent, orderHandling.percent / 100, orderHandling.realPercentage / 100);

            PrintTable.PrintConsole(resPrint);
            int     useCase      = 0;
            decimal difPrecentge = 0;

            System.Threading.Thread.Sleep(orderHandling.OrderToCare.ExtraPercent.WaitingTimeForNextPriceUpdate);
            orderHandling.OrderToCare.Result = TradeUseCase.OrderDetails(orderHandling.OrderToCare.Result);

            DateTime startTimeSmallAmount = DateTime.Now;

            while (!orderHandling.OrderToCare.Done)
            {
                if (orderHandling.OrderToCare.itsCanAdded & orderHandling.OrderToCare.itsCanUpdate)
                {
                    startTimeSmallAmount = DateTime.Now;
                    if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.FilledPartially)
                    {
                        difPrecentge = orderHandling.OrderToCare.Result.AmountFilled / orderHandling.OrderToCare.Result.Amount;
                        if (difPrecentge > 0.99m)
                        {
                            useCase = 4; // Current Order Cancellation
                        }
                        else
                        {
                            useCase = 3;  // We will also update the price in addition to the quantity update
                        }
                    }
                    else // if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Pending)
                    {
                        useCase = 1; // Update price
                    }

                    TradeUseCase.Start(useCase, orderHandling);
                }
                else if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Filled)
                {
                    return(true);
                }
                else if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.FilledPartially)
                {
                    if (firstOrder)     // We will cancel an order only in the case of a first order, because in other orders we will want the order to remain until it is executed
                    {
                        DateTime timeSmallAmount = DateTime.Now;
                        if (!(timeSmallAmount.Subtract(startTimeSmallAmount).TotalMinutes > 1))                                                                              // Limit of waiting for order to 1 minute
                        {
                            if ((orderHandling.OrderToCare.Result.AmountFilled + orderHandling.OrderToCare.AmountFilledDifferentOrderNumber) < orderHandling.minAmountTrade) // try fix bug of buying a small amount of coins, In use case of the quantity is less than the minimum for the trade, we will continue to wait until at least the required minimum is filled
                            {
                                continue;
                            }
                        }
                        else
                        {
                            useCase = 4; // Current Order Cancellation
                            TradeUseCase.Start(useCase, orderHandling);

                            if (orderHandling.OrderToCare.amountFilled < orderHandling.minAmountTrade)  // try fix bug of buying a small amount of coins, In use case of the quantity is less than the minimum for the trade, we will continue to wait until at least the required minimum is filled
                            {
                                ExchangeOrderRequest revertOrder = new ExchangeOrderRequest();
                                try
                                {
                                    revertOrder.Amount    = orderHandling.OrderToCare.amountFilled;
                                    revertOrder.IsBuy     = false;
                                    revertOrder.OrderType = StaticVariables.orderType;
                                    revertOrder.Price     = orderHandling.OrderToCare.Request.Price * (1 + (StaticVariables.FeeTrade * 2));
                                    revertOrder.Symbol    = orderHandling.OrderToCare.Request.Symbol;
                                    OrderTrade revertOrderTrade = new OrderTrade(revertOrder);
                                    revertOrderTrade.Result = StaticVariables.api.PlaceOrder(revertOrder);

                                    PrintTable.Start(StaticVariables.pathWithDate + "Small_Amount_Handling.csv", orderHandling.OrderToCare.Result.PrintSymbol(), "OrderResultSymbol");
                                    PrintTable.Start(StaticVariables.pathWithDate + "Small_Amount_Handling.csv", revertOrderTrade.Result.PrintSymbol(), "OrderResultSymbol");
                                }
                                catch (Exception ex)
                                {
                                    StaticVariables.Wallet = WalletFunc.GetWallet();     // Wallet update. Because part of the trade was carried out. Apparently the amounts of coins have changed

                                    string warningMessage = String.Format("{0},\tamountFilled - {1},\tAmount - {2},\tminAmountTrade - {3},", orderHandling.OrderToCare.request.Symbol, orderHandling.OrderToCare.amountFilled, orderHandling.OrderToCare.request.Amount, orderHandling.minAmountTrade);
                                    PrintTable.PrintConsole(warningMessage);
                                    PrintFunc.AddLine(StaticVariables.pathWithDate + "Small_Amount_Left.txt", warningMessage);
                                    PrintTable.Start(StaticVariables.pathWithDate + "Small_Amount_Left.csv", orderHandling.OrderToCare.request.Print(), "OrderResult");

                                    DateTime localDate   = DateTime.Now;
                                    string   printResult = String.Format("{0}\n{1}", localDate.ToString(), ex.ToString());
                                    PrintException.Start("Small_Amount_Left", printResult);
                                }
                            }

                            return(orderHandling.OrderToCare.succsseFirstOrder);
                        }
                    }
                    else
                    {
                        orderHandling.OrderToCare.ItsOrderLeft = true;
                        return(false);
                    }
                }
                else if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Pending)
                {
                    if (firstOrder)     // We will cancel an order only in the case of a first order, because in other orders we will want the order to remain until it is executed
                    {
                        useCase = 4;    // Current Order Cancellation
                        TradeUseCase.Start(useCase, orderHandling);
                        return(orderHandling.OrderToCare.succsseFirstOrder);
                    }
                    else
                    {
                        orderHandling.OrderToCare.ItsOrderLeft = true;
                        return(false);
                    }
                }


                if (!orderHandling.OrderToCare.Done)
                {
                    System.Threading.Thread.Sleep(orderHandling.OrderToCare.ExtraPercent.WaitingTimeForNextPriceUpdate);
                    orderHandling.OrderToCare.Result = TradeUseCase.OrderDetails(orderHandling.OrderToCare.Result);
                    if (orderHandling.OrderToCare.Result.Result == ExchangeAPIOrderResult.Canceled)     // In case a cancellation was made by the stock exchange due to an order or quantity error
                    {
                        bool checkCancel = CancellationFunc.ReviewCancellationAndUpdateOrder(orderHandling);

                        if (firstOrder)
                        {
                            return(orderHandling.OrderToCare.succsseFirstOrder);
                        }
                        else
                        {
                            // TODO Check what amount has not traded. Maybe by the wallet. Update amount and send request in the current function
                        }
                    }
                }
            }

            if (firstOrder)
            {
                return(orderHandling.OrderToCare.succsseFirstOrder);   //  amountFilled > minAmaunt
            }
            else
            {
                return(orderHandling.OrderToCare.succsseTrade);                 // ((amountFilled == amountStart) || (amountFilled >= amountFinish))
            }
        }
Example #8
0
        public static void Start(bool fullSymbol = false)
        {
            List <string> SymbolsList = StaticVariables.api.GetSymbolsNormalize();

            SymbolsList.Sort();
#if DEBUG
            PrintFunc.PrintList(SymbolsList, "SymbolsList_beforeRemove", StaticVariables.pathDataDebug);
            List <string> SymbolsListRemove = new List <string>();
#endif
            List <string>            currencyList = new List <string>();
            Dictionary <string, int> paymentList  = new Dictionary <string, int>();
            string[] currency_payment;
            string   currency;
            string   payment;
            for (int g = 0; g < SymbolsList.Count; g++)
            {
                currency_payment = SymbolsList[g].Split('_');
                currency         = currency_payment[0];
                payment          = currency_payment[1];

                if (Remove(payment))
                {
#if DEBUG
                    SymbolsListRemove.Add(SymbolsList[g]);
#endif

                    SymbolsList.Remove(SymbolsList[g]);  // For the purpose of saving running time in the following loops
                    g--;                                 // Because we removed the value in the current index, then the next loop should use the current index that contains the following value
                }
                else
                {
                    currencyList.Add(currency);
                    if (paymentList.Keys.Contains(payment))
                    {
                        paymentList[payment] = paymentList[payment] + 1;
                    }
                    else
                    {
                        paymentList.Add(payment, 1);
                    }
                }
            }

#if DEBUG
            PrintFunc.PrintList(SymbolsList, "SymbolsList_afterRemove", StaticVariables.pathDataDebug);
            PrintFunc.PrintList(SymbolsListRemove, "SymbolsListRemove", StaticVariables.pathDataDebug);
#endif

            StaticVariables.PaymentListByWeight = paymentList.OrderByDescending(x => x.Value).Select(y => y.Key).ToList();
            currencyList = currencyList.Distinct().ToList();

            WalletFunc.InitializationStaticLists(SymbolsList);
            WalletFunc.ConversionPayment();
            Dictionary <string, ExchangeTicker> allTickers = StaticVariables.api.GetTickers();
            StaticVariables.maxTradeInPaymentWeighted = WalletFunc.GetMaxAmount(allTickers);
            //DataTable symboleDB = GetDB(GetExtraPercentFromDB);

            Dictionary <string, List <string> > listCurrenciesAndPayment = new Dictionary <string, List <string> >();
            StaticVariables.symbolsDateList = new Dictionary <string, List <SymbolsDate> >();


            // Use a reference. For the purpose of machine learning and the use of databases
            StaticVariables.magicNumberList = DBfunc.GetMagicNumberTable();
            if (StaticVariables.magicNumberList.Count > 0)
            {
                WaitingTimeML.Start();      // USE to ML_4
            }

#if DEBUG
            PrintFunc.PrintList(SymbolsList, "SymbolsList_afterDistinct", StaticVariables.pathDataDebug);
            PrintFunc.PrintDictionary(allTickers, "allTickers", StaticVariables.pathDataDebug);
#endif
            for (int i = 0; i < currencyList.Count; i++)
            {
                currency = currencyList[i];
                List <string>      paymentCurrencyList = new List <string>();
                List <SymbolsDate> tempSymbolsDateList = new List <SymbolsDate>();
                SymbolsDate        tempSymbolsDate;
                ExchangeTicker     tempTicker;
                MagicNumber        magicNumber;
                string             symbole;
                for (int j = 0; j < SymbolsList.Count; j++)
                {
                    symbole          = SymbolsList[j];
                    currency_payment = symbole.Split('_');
                    if (currency_payment[0].Equals(currency))
                    {
                        paymentCurrencyList.Add((fullSymbol ? SymbolsList[j] : currency_payment[1]));

                        if (!allTickers.TryGetValue(symbole, out tempTicker))
                        {
                            SymbolsList.Remove(symbole);
                            j--;
                            continue;
                        }

                        magicNumber     = DBfunc.GetMagicNumberItem(symbole, currency);
                        tempSymbolsDate = new SymbolsDate(symbole, tempTicker, magicNumber);
                        tempSymbolsDateList.Add(tempSymbolsDate);

                        if (StaticVariables.PaymentListByWeight.Contains(currency))
                        {
                            StaticVariables.listArbitrageSymbolsDate[symbole] = tempSymbolsDate;
                        }

                        SymbolsList.Remove(symbole);  // For the purpose of saving running time in the following loops
                        j--;                          // Because we removed the value in the current index, then the next loop should use the current index that contains the following value
                    }
                }

                if (paymentCurrencyList.Count > 1)
                {
                    paymentCurrencyList.Sort();
                    listCurrenciesAndPayment.Add(currency, paymentCurrencyList);
                    StaticVariables.symbolsDateList.Add(currency, tempSymbolsDateList);
                }
            }

            DBfunc.AddMagicNumberTable(StaticVariables.magicNumberList);
            return;
        }
Example #9
0
        public static OrderHandling ArbitragePercent(string currency, List <SymbolsDate> list)
        {
#if DEBUG
            DateTime timeOrder = DateTime.Now;
            FindDebug = String.Format("{0}\n", timeOrder);
#endif


            OrderHandling package        = null;
            int           sumListToCheck = ListToCheck(list);
            if (sumListToCheck < 2)
            {
                return(package);
            }

            Dictionary <string, decimal> BuyPriceList  = new Dictionary <string, decimal>();
            Dictionary <string, decimal> SellPriceList = new Dictionary <string, decimal>();

            ExchangeOrderBook book;
            string            symbole;
            decimal           priceBuy;
            decimal           priceSell;
            for (int i = 0; i < list.Count; i++)
            {
                if (!list[i].itsAvalible)
                {
                    continue;
                }

                symbole  = list[i].symbole;
                book     = StaticVariables.api.GetOrderBook(symbole, StaticVariables.maxCount);
                priceBuy = GetPrice(book, list[i], true);
                if (priceBuy != 0)
                {
                    BuyPriceList.Add(symbole, priceBuy);
                }

                priceSell = GetPrice(book, list[i], false);
                if (priceSell != 0)
                {
                    SellPriceList.Add(symbole, priceSell);
                }
            }

            string  BuyKey    = "";
            string  SellKey   = "";
            decimal BuyPrice  = 0;
            decimal SellPrice = 0;

            while (BuyKey == SellKey)
            {
                // Get the lowest price. So sorting Descending
                BuyKey   = BuyPriceList.OrderByDescending(x => x.Value).Select(y => y.Key).ToList().Last();
                BuyPrice = BuyPriceList[BuyKey];

                // Getting the highest price. That's why sorting is normal
                SellKey   = SellPriceList.OrderBy(x => x.Value).Select(y => y.Key).ToList().Last();
                SellPrice = SellPriceList[SellKey];

#if DEBUG
                FindDebug += String.Format("BuyPriceList\n{0}\n", PrintFunc.PrintDictionary(BuyPriceList));
                FindDebug += String.Format("SellPriceList\n{0}\n", PrintFunc.PrintDictionary(SellPriceList));
                FindDebug += String.Format("BuyKey - {0}\tBuyPrice - {1}\n", BuyKey, BuyPrice);
                FindDebug += String.Format("SellKey - {0}\tSellPrice - {1}\n", SellKey, SellPrice);
#endif

                if (BuyKey != SellKey)
                {
                    break;
                }

                // Handling in case of buying and selling from the same currency
                int indexBuyPriceList  = BuyPriceList.Count;
                int indexSellPriceList = SellPriceList.Count;
                if (indexBuyPriceList < 2 || indexSellPriceList < 2)
                {
                    return(package);
                }

                // indexBuyPriceList-2 -> This is the index of the next proposal
                decimal BuyNextOffer         = BuyPriceList.ElementAt(indexBuyPriceList - 2).Value;
                decimal BuyNextOfferDifrent  = BuyNextOffer - BuyPrice;
                decimal SellNextOffer        = SellPriceList.ElementAt(indexSellPriceList - 2).Value;
                decimal SellNextOfferDifrent = SellPrice - SellNextOffer;

                if (BuyNextOfferDifrent > SellNextOfferDifrent)
                {
                    SellPriceList.Remove(SellKey);
                }
                else
                {
                    BuyPriceList.Remove(BuyKey);
                }

#if DEBUG
                FindDebug += String.Format("BuyNextOffer - {0}\tBuyNextOfferDifrent - {1}\n", BuyNextOffer, BuyNextOfferDifrent);
                FindDebug += String.Format("SellNextOffer - {0}\tSellNextOfferDifrent - {1}\n", SellNextOffer, SellNextOfferDifrent);
                FindDebug += String.Format("(BuyNextOfferDifrent > SellNextOfferDifrent) - {0}\n", (BuyNextOfferDifrent > SellNextOfferDifrent));
#endif
            }


            decimal precent = 0;
            try
            {
                precent = ((SellPrice - BuyPrice) / BuyPrice) * 100;
            }
            catch (Exception)
            {
                // Division by zero
                return(package);
            }


            SymbolsDate buy = (from item in list where item.Symbole == BuyKey select item).FirstOrDefault();
            buy.ItsBuy = true;

            SymbolsDate sell = (from item in list where item.Symbole == SellKey select item).FirstOrDefault();
            sell.ItsBuy = false;

            // After activating the magic number by buying.ItsBuy / buy.ItsBuy we will check the prices and the percentage of potential profit
            decimal buyPricePotential  = WalletFunc.ConversionPrice(buy.orderTrade.request.Price, buy.payment);
            decimal sellPricePotential = WalletFunc.ConversionPrice(sell.orderTrade.request.Price, sell.payment);
            decimal percentPotential   = 0;

            try
            {
                percentPotential = ((sellPricePotential - buyPricePotential) / buyPricePotential) * 100;
            }
            catch (Exception)
            {
                // Division by zero
                return(package);
            }

#if DEBUG
            FindDebug += String.Format("precent - {0:P3}\n", precent / 100);
            FindDebug += String.Format("after implemation ExtraPercent\textraPercent.Percent - {0:P2}\n", buy.orderTrade.extraPercent.Percent);
            FindDebug += String.Format("buy.Price - {0:N8}\tbuyPricePotential (ConversionPrice) - {1:N8}\n", buy.orderTrade.request.Price, buyPricePotential);
            FindDebug += String.Format("after implemation ExtraPercent\textraPercent.Percent - {0:P2}\n", sell.orderTrade.extraPercent.Percent);
            FindDebug += String.Format("sell.Price - {0:N8}\tsellPricePotential (ConversionPrice) - {1:N8}\n", sell.orderTrade.request.Price, sellPricePotential);
            FindDebug += String.Format("percentPotential - {0:P3}\n\n\n", percentPotential / 100);
            PrintFunc.AddLine(StaticVariables.pathFindDebug + "Find_" + currency + ".txt", FindDebug);
#endif

            package                    = new OrderHandling(precent, currency, buy, sell);
            package.buyPrice           = WalletFunc.ConversionPrice(buy.orderTrade.maxOrMinPrice, buy.payment);
            package.sellPrice          = WalletFunc.ConversionPrice(sell.orderTrade.maxOrMinPrice, sell.payment);
            package.buyPricePotential  = buyPricePotential;
            package.sellPricePotential = sellPricePotential;
            package.percentPotential   = percentPotential;

            return(package);
        }
Example #10
0
        public static decimal GetPrice(ExchangeOrderBook book, SymbolsDate item, bool buy)
        {
            decimal price  = 0;
            decimal amaunt = 0;
            int     j      = 0;

            do
            {
                if (buy)
                {
                    if (book.Asks.Count <= j)
                    {
                        return(0);
                    }

                    price  = book.Asks[j].Price;
                    amaunt = book.Asks[j].Amount;
                }
                else
                {
                    if (book.Bids.Count <= j)
                    {
                        return(0);
                    }

                    price  = book.Bids[j].Price;
                    amaunt = book.Bids[j].Amount;
                }

                j++;

                if (j == StaticVariables.maxCount) //  In case the first 5 orders in the bookOrder are below the minimum required quantity
                {
                    StaticVariables.maxCount = 10;
                    return(0);
                }

                if (!buy)
                {
                    item.MinAmount = price;
                }
            } while (amaunt < item.MinAmount);

            ExchangeOrderRequest request = new ExchangeOrderRequest();

            request.Amount    = amaunt;
            request.IsBuy     = buy;
            request.OrderType = StaticVariables.orderType;
            request.Price     = price;
            request.Symbol    = item.symbole;

            OrderTrade orderTrade = new OrderTrade(request);

            if (buy)
            {
                item.buyOrderTrade = orderTrade;
            }
            else
            {
                item.sellOrderTrade = orderTrade;
            }

            price = WalletFunc.ConversionPrice(price, item.payment);

#if DEBUG
            FindDebug += String.Format("{0}\tSymbol - {1}\n", (request.IsBuy ? "Buy" : "Sell"), request.Symbol);
            FindDebug += String.Format("while (amaunt < item.MinAmount) count - {0}\n", j);
            FindDebug += String.Format("MinAmount - {0}\n", item.MinAmount);
            FindDebug += String.Format("request - {0}\n", request.Print());
            FindDebug += String.Format("price - {0}\n\n", price);
#endif

            return(price);
        }