Example #1
0
        public static void TakeProfit(IDbService dbService, IExchange baseExchange, IExchange counterExchange, decimal margin)
        {
            try
            {
                var baseBalances    = baseExchange.GetBalances().Result.ToDictionary(b => b.Currency);
                var counterBalances = counterExchange.GetBalances().Result.ToDictionary(b => b.Currency);

                var pairs = dbService.GetArbitragePairs("market", baseExchange.Name, counterExchange.Name).Select(p => new ArbitragePair(p));

                var completedCurrencies = new Dictionary <string, bool>();

                foreach (var pair in pairs)
                {
                    if (!completedCurrencies.ContainsKey(pair.MarketCurrency))
                    {
                        decimal baseQuantity = Helper.RoundQuantity(pair, baseBalances[pair.MarketCurrency].Available * margin);
                        var     baseResult   = baseExchange.MarketSell(pair.Symbol, baseQuantity).Result;

                        decimal counterQuantity = Helper.RoundQuantity(pair, counterBalances[pair.MarketCurrency].Available * margin);
                        var     counterResult   = counterExchange.MarketSell(pair.Symbol, counterQuantity).Result;
                        completedCurrencies.TryAdd(pair.MarketCurrency, true);
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
        }
Example #2
0
 private void TimerUpdateCurrencies_Tick(object sender, EventArgs e)
 {
     Task.Factory.StartNew(() =>
     {
         Exchange.GetOrderHistory();
         Exchange.GetBalances();
     });
 }
        public async Task DoWork(IEnumerable <ArbitragePair> pairs, CancellationToken token)
        {
            try
            {
                baseBalances.Clear();
                counterBalances.Clear();
                completedPairs.Clear();

                var bBalances = await baseExchange.GetBalances();

                var cBalances = await counterExchange.GetBalances();

                foreach (var b in bBalances)
                {
                    //Prevent balancing crumbs
                    if (b.Available > 0.01m)
                    {
                        baseBalances.TryAdd(b.Currency, b);
                    }
                }

                foreach (var b in cBalances)
                {
                    //Prevent balancing crumbs
                    if (b.Available > 0.01m)
                    {
                        counterBalances.TryAdd(b.Currency, b);
                    }
                }


                //      BalanceCurrency("BTC");
                //       BalanceCurrency("ETH");

                foreach (var pair in pairs)
                {
                    try
                    {
                        if (baseBalances.ContainsKey(pair.MarketCurrency) && counterBalances.ContainsKey(pair.MarketCurrency) && !completedPairs.ContainsKey(pair.MarketCurrency))
                        {
                            //  BalanceCurrency(pair.MarketCurrency);
                        }
                        AuditCompletedOrdersForPair(pair, token);
                    }
                    catch (Exception ex)
                    {
                        logger.Error(new { Exception = ex.Message, pair = pair.Symbol });
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
Example #4
0
        private async void Form1_Load(object sender, EventArgs e)
        {
            Exchange = new BinanceWrapper();


            //Get a list of all coins (and whether we have any)
            await Exchange.GetBalances();

            var usdt = Coin.AllCoins.Where(c => c.Currency == "USDT").FirstOrDefault();
            var btc  = Coin.AllCoins.Where(c => c.Currency == "BTC").FirstOrDefault();

            //Get a list of all the stuff we ahve bought and sold (to establish profit and baseline)
            //await Exchange.GetOrderHistory();
            foreach (var coin in Coin.AllCoins.Where(c => c.Balance > 0))
            {
                var mostrecentorder = Order.AllOrders.Where(o => o.Exchange == "BTC-" + coin.Currency).OrderByDescending(o => o.TimeStamp).FirstOrDefault();
                if (mostrecentorder != null)
                {
                    coin.LastPurchasePrice = mostrecentorder.PricePerUnit;
                }
                var candlestick = await Exchange.GetCandleSticks(market, TimeInterval.Minutes_15);

                c.Candles.AddRange(candlestick);
                try
                {
                    flowLayoutPanel1.Controls.Add(CreateCurrencyGroup(coin));
                }
                catch (Exception) { }
            }
            //FillOrders();
            //FillAlerts();
            timerTicker.Tick += UpdateCurrencyTickers;
            timerTicker.Start();
            timerUpdateCurrencies.Tick += TimerUpdateCurrencies_Tick;
            timerUpdateCurrencies.Start();

            //This handles new currencies (trading on the exchange and not through this interface)
            if (Coin.AllCoins.Count > 0)
            {
                BTCValue = Coin.AllCoins.Where(c => c.Currency == "BTC").First().ValueInUSD;
            }
            this.Text = "CryptoDayTrader BTC:" + BTCValue;

            lblTotalPortfolioValueUSD.Text = "Total Value in USD: $" + Math.Round(Coin.AllCoins.Sum(c => (c.LastPurchasePrice * c.Balance) * BTCValue), 4).ToString();
            lblTotalPortfolioValueBTC.Text = "Total Value in BTC: " + Coin.AllCoins.Sum(c => (c.LastPurchasePrice * c.Balance)).ToString();
            Task.Factory.StartNew(() => {
                //This adds ADDITIONAL information to currencies - so we dont need it right away.
                Exchange.GetCurrencies();
            });
        }
Example #5
0
        public async Task TakeBalanceSnapshot()
        {
            try
            {
                var pairs = dbService.GetArbitragePairs("", baseExchange.Name, counterExchange.Name).Select(p => new ArbitragePair(p));

                var summaries = await baseExchange.MarketSummaries();

                var tickers = summaries.Where(s => s.BaseCurrency == "BTC" || s.QuoteCurrency == "BTC").ToDictionary(s => s.QuoteCurrency);

                var bs = await baseExchange.GetBalances();

                var cs = await counterExchange.GetBalances();

                var baseBalances    = bs.ToDictionary(b => b.Currency);
                var counterBalances = cs.ToDictionary(c => c.Currency);

                //First take BTC snapshot
                if (tickers.ContainsKey("BTC"))
                {
                    InsertBalanceSnapshot("USD", tickers["BTC"].Last, baseBalances, counterBalances);
                    InsertBalanceSnapshot("BTC", 1, baseBalances, counterBalances);
                }
                else
                {
                    logger.Error("No Ticker for BTC Balance Snapshot");
                }

                foreach (var pair in pairs.Where(p => p.BaseCurrency == "BTC"))
                {
                    if (tickers.ContainsKey(pair.MarketCurrency))
                    {
                        InsertBalanceSnapshot(pair.MarketCurrency, tickers[pair.MarketCurrency].Last, baseBalances, counterBalances);
                    }
                    else
                    {
                        logger.Error("No Ticker for {0} Balance Snapshot", pair.MarketCurrency);
                    }
                }
            }
            catch (ApiException ae)
            {
                logger.Error(JsonConvert.SerializeObject(JsonConvert.DeserializeObject(ae.Content), Formatting.Indented));
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
        }
Example #6
0
        public void QueryBalance()
        {
            while (running)
            {
                List <string> coins = new List <string>();
                coins.Add(coin1);
                coins.Add(coin2);

                List <Balance> balances = currentExchange.GetBalances(coins, apiID, secret);
                controller.NotifyBalanceChanged(balances);

                if (balances.Count == 2)
                {
                    currentBalance1 = balances[0].Available;
                    currentBalance2 = balances[1].Available;
                }

                Thread.Sleep(500);
            }
        }
        public async Task <BalanceInformation> GetBalance()
        {
            List <WalletBalance> bittrexBalances;

            try
            {
                var response = await _exchange.GetBalances();

                bittrexBalances = TradeConverter.BittrexToWalletBalances(response);
            }
            catch (Exception e)
            {
                _log.LogError("Error in getting balances from bittrex: " + e.Message);
                throw;
            }

            var totalBtcBalance = 0m;

            foreach (var balance in bittrexBalances)
            {
                if (balance.Balance == 0)
                {
                    continue;
                }

                decimal price;
                decimal btcAmount;
                decimal boughtPrice = 0m;

                switch (balance.Currency)
                {
                case "BTC":
                    btcAmount   = balance.Balance;
                    price       = 1;
                    boughtPrice = 1;
                    break;

                case "USDT":
                    price = await GetPrice(balance.Currency);

                    btcAmount = (balance.Balance / price);
                    var lastTradeForPair = _databaseService.GetLastTradeForPair(balance.Currency, Constants.Bittrex, TradeSide.Buy);
                    if (lastTradeForPair != null)
                    {
                        boughtPrice = lastTradeForPair.Limit;
                    }
                    break;

                default:
                    price = await GetPrice(balance.Currency);

                    btcAmount = (price * balance.Balance);
                    var lastTradeForPair1 = _databaseService.GetLastTradeForPair(balance.Currency, Constants.Bittrex, TradeSide.Buy);
                    if (lastTradeForPair1 != null)
                    {
                        boughtPrice = lastTradeForPair1.Limit;
                    }
                    break;
                }

                try
                {
                    balance.PercentageChange = ProfitCalculator.PriceDifference(price, boughtPrice);
                }
                catch
                {
                    // There maybe a divide by 0 issue if we couldn't find the last trade. Its fine. Just print zero
                    balance.PercentageChange = 0;
                }
                balance.BtcAmount = btcAmount;
                balance.Price     = price;
                totalBtcBalance   = totalBtcBalance + btcAmount;
            }

            var lastBalance  = _databaseService.GetBalance24HoursAgo(Constants.Bittrex);
            var dollarAmount = await _priceService.GetDollarAmount(totalBtcBalance);

            var currentBalance = _databaseService.AddBalance(totalBtcBalance, dollarAmount, Constants.Bittrex);

            return(new BalanceInformation(currentBalance, lastBalance, Constants.Bittrex, bittrexBalances));
        }