private async Task <CryptoTransaction[]> MappTransaction(CoinbaseTransaction transaction, Guid exchangeId)
        {
            switch (transaction.Type)
            {
            case CoinbaseTransactionTypes.Buy:

                var transactions = new List <CryptoTransaction>()
                {
                    CryptoTransaction.NewTrade(transaction.Buy.User_Reference, transaction.Created_At, exchangeId, transaction.Details.Title + " " + transaction.Details.SubTitle,
                                               transaction.Buy.Amount.Amount,
                                               transaction.Buy.Amount.Currency,
                                               transaction.Buy.Fee.Amount,
                                               transaction.Buy.Fee.Currency,
                                               transaction.Buy.Subtotal.Amount,
                                               transaction.Buy.Subtotal.Currency,
                                               await _marketData.GetHistoricRate("CHF", transaction.Buy.Amount.Currency, transaction.Created_At))
                };

                if (await IsCreditcardPayment(transaction.Buy.Payment_Method.Id))
                {
                    // Add Second transaction for creditcard payment
                    transactions.Add(CryptoTransaction.NewIn("Creditcard in from buy " + transaction.Buy.User_Reference, transaction.Created_At.AddSeconds(-2), exchangeId, transaction.Details.Title + " " + transaction.Details.SubTitle,
                                                             transaction.Buy.Fee.Amount + transaction.Buy.Subtotal.Amount,
                                                             transaction.Buy.Subtotal.Currency,
                                                             transaction.Details.Payment_Method_Name,
                                                             "Coinbase",
                                                             string.Empty));
                }

                return(transactions.ToArray());

            //case CoinbaseTransactionTypes.Sell:
            //    crypto.SellAmount = transaction.Sell.Amount.Amount;
            //    crypto.SellCurrency= transaction.Sell.Amount.Currency;
            //    crypto.FeeAmount = transaction.Sell.Fee.Amount;
            //    crypto.FeeCurrency = transaction.Buy.Fee.Currency;
            //    break;

            //case CoinbaseTransactionTypes.Transfer:
            //    break;
            case CoinbaseTransactionTypes.Send:
                // Send or receive
                if (transaction.Network.Status == CoinbaseTransactionStatus.Off_Blockchain)
                {
                    // Is Coinbase gift
                    return new[] { CryptoTransaction.NewIn(transaction.Id, transaction.Created_At, exchangeId,
                                                           transaction.Details.Title + " " + transaction.Details.SubTitle,
                                                           transaction.Amount.Amount,
                                                           transaction.Amount.Currency,
                                                           "Coinbase",
                                                           string.Empty,
                                                           transaction.Network.Hash) }
                }
                ;

                if (transaction.To == null)
                {
                    // Is Receiving
                    return(new[] { CryptoTransaction.NewIn(transaction.Network.Hash, transaction.Created_At, exchangeId,
                                                           transaction.Details.Title + " " + transaction.Details.SubTitle,
                                                           transaction.Amount.Amount,
                                                           transaction.Amount.Currency,
                                                           string.Empty, // Todo: Get Network adress
                                                           string.Empty,
                                                           transaction.Network.Hash) });
                }
                else
                {
                    // Is Sending
                    return(new[] { CryptoTransaction.NewOut(transaction.Network.Hash, transaction.Created_At, exchangeId,
                                                            transaction.Details.Title + " " + transaction.Details.SubTitle,
                                                            transaction.Network.Transaction_Amount.Amount,
                                                            transaction.Network.Transaction_Amount.Currency,
                                                            transaction.Network.Transaction_Fee.Amount,
                                                            transaction.Network.Transaction_Fee.Currency,
                                                            string.Empty,
                                                            transaction.To.Address,
                                                            transaction.Network.Hash) });
                }

            case CoinbaseTransactionTypes.Fiat_Deposit:
                return(new[] { CryptoTransaction.NewIn(transaction.Fiat_Deposit.User_Reference, transaction.Created_At, exchangeId,
                                                       transaction.Details.Title + " " + transaction.Details.SubTitle,
                                                       transaction.Fiat_Deposit.Amount.Amount,
                                                       transaction.Fiat_Deposit.Amount.Currency,
                                                       string.Empty,
                                                       string.Empty,
                                                       string.Empty) });

            ////case CoinbaseTransactionTypes.Fiat_Withdrawal:
            ////    break;
            case CoinbaseTransactionTypes.Exchange_Deposit:
                //    // Moved to GDAX
                return(new[] { CryptoTransaction.NewOut(transaction.Id, transaction.Created_At, exchangeId,
                                                        transaction.Details.Title + " " + transaction.Details.SubTitle,
                                                        -1 * transaction.Amount.Amount,
                                                        transaction.Amount.Currency,
                                                        0,
                                                        string.Empty,
                                                        string.Empty,
                                                        transaction.Details.SubTitle,
                                                        string.Empty) });

            case CoinbaseTransactionTypes.Exchange_Withdrawal:
                // From GDAX
                return(new[] { CryptoTransaction.NewIn(transaction.Id, transaction.Created_At, exchangeId,
                                                       transaction.Details.Title + " " + transaction.Details.SubTitle,
                                                       transaction.Amount.Amount,
                                                       transaction.Amount.Currency,
                                                       transaction.Details.SubTitle,
                                                       string.Empty,
                                                       string.Empty) });

            default:
                Logger.Error("Transaction Type not handled: {0}", transaction.Type);
                throw new ArgumentOutOfRangeException();
            }
        }
Example #2
0
        public async Task <IEnumerable <CryptoTransaction> > GetTransactions(Exchange exchange)
        {
            var client = new RestClient("https://bity.com/");


            var authRequest = new RestRequest("o/token/", Method.POST);

            authRequest.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            authRequest.AddHeader("Accept", "application/json, text/plain, */*");
            authRequest.AddParameter("client_id", "QmaTkYI50XmCF18fupZgdAOptYqDzVix12RpqFYS");
            authRequest.AddParameter("grant_type", "password");
            authRequest.AddParameter("username", exchange.PublicKey);
            authRequest.AddParameter("password", exchange.Passphrase);

            var authResp = await client.Execute(authRequest);

            var token = JsonConvert.DeserializeObject <BityAuthResponse>(authResp.Content);


            var historyRequest = new RestRequest("/api/v1/order/?limit=100&offset=0&order_by=-timestamp_created", Method.GET);

            historyRequest.AddHeader("Authorization", token.Token_Type + " " + token.Access_Token);
            var historyResponse = await client.Execute(historyRequest);


            var data     = JsonConvert.DeserializeObject <Orders>(historyResponse.Content);
            var executed = data.Objects.Where(o => o.Status == "EXEC");

            var transactions = new List <CryptoTransaction>();

            foreach (var trade in executed)
            {
                var inputCurrency  = trade.Inputtransactions.First().Currency;
                var inputAmount    = trade.Inputtransactions.Sum(i => i.Amount);
                var outputCurrency = trade.Outputtransactions.First().Currency;
                var outputAmount   = trade.Outputtransactions.Sum(o => o.Amount);
                var fee            = trade.Outputtransactions.Sum(o => o.PaymentProcessorFee) +
                                     trade.Inputtransactions.Sum(i => i.PaymentProcessorFee);
                var date            = trade.TimestampCreated;
                var inputReference  = trade.Inputtransactions.First().Reference;
                var outputReference = trade.Outputtransactions.First().Reference;
                var fiatRate        = await _marketData.GetHistoricRate("CHF", outputCurrency, date);

                // Input Transaction
                transactions.Add(CryptoTransaction.NewIn(
                                     inputReference,
                                     date,
                                     exchange.Id,
                                     "Receving",
                                     inputAmount,
                                     inputCurrency,
                                     inputReference,
                                     string.Empty,
                                     string.Empty
                                     ));

                // Trade
                transactions.Add(CryptoTransaction.NewTrade(
                                     inputReference + " to " + outputReference,
                                     date,
                                     exchange.Id,
                                     "Trade", outputAmount,
                                     outputCurrency,
                                     (decimal)fee,
                                     "Unknown Currency",
                                     inputAmount,
                                     inputCurrency,
                                     fiatRate
                                     ));

                // Output Transaction
                transactions.Add(CryptoTransaction.NewOut(
                                     outputReference,
                                     date,
                                     exchange.Id,
                                     "Sending",
                                     outputAmount,
                                     outputCurrency,
                                     (decimal)fee,
                                     "Unknown Currency",
                                     string.Empty,
                                     string.Empty,
                                     outputReference
                                     ));
            }

            return(transactions);
        }
Example #3
0
        private async Task <IEnumerable <CryptoTransaction> > GetTrades(BinanceClient client, Exchange exchange)
        {
            var trades = new List <CryptoTransaction>();
            var prices = await client.GetAllPricesAsync();

            var counter = 0;

            foreach (var binancePrice in prices.Data)
            {
                var symbol = binancePrice.Symbol;
                Logger.Debug("Ask " + symbol + " (" + counter++ + "/" + prices.Data.Length + ")");
                string currency1 = null, currency2 = null;

                if (symbol.EndsWith("BTC"))
                {
                    // Is BTC
                    currency1 = "BTC";
                    currency2 = symbol.Replace("BTC", "");
                }

                if (symbol.EndsWith("ETH"))
                {
                    // Is ETH
                    currency1 = "ETH";
                    currency2 = symbol.Replace("ETH", "");
                }

                if (symbol.EndsWith("BNB"))
                {
                    // Is BNB
                    currency1 = "BNB";
                    currency2 = symbol.Replace("BNB", "");
                }

                if (symbol.EndsWith("USDT"))
                {
                    // Is USDT
                    currency1 = "USDT";
                    currency2 = symbol.Replace("USDT", "");
                }

                if (currency1 == null || currency2 == null)
                {
                    if (symbol == "123456")
                    {
                        Logger.Warn("{0} symbol is not supported", symbol);
                        continue;
                    }

                    Logger.Error("Unknown symbol: {0}. Aborting!", symbol);

                    throw new ArgumentOutOfRangeException("Unknown symbol: " + symbol);
                }

                // Rename Bitcoin cash
                if (currency2 == "BCC")
                {
                    currency2 = "BCH";
                }

                var binanceApiResult = await client.GetMyTradesAsync(symbol);

                if (binanceApiResult.Success)
                {
                    foreach (var trade in binanceApiResult.Data)
                    {
                        if (trade.IsBuyer)
                        {
                            // Buy
                            trades.Add(
                                CryptoTransaction.NewTrade(trade.Id.ToString(), trade.Time, exchange.Id, "Binance Buy",
                                                           trade.Quantity, currency2, trade.Commission, trade.CommissionAsset,
                                                           trade.Price * trade.Quantity,
                                                           currency1, await _marketData.GetHistoricRate("CHF", currency2, trade.Time))
                                );
                        }
                        else
                        {
                            // Sell
                            trades.Add(
                                CryptoTransaction.NewTrade(trade.Id.ToString(), trade.Time, exchange.Id, "Binance Sell",
                                                           trade.Price * trade.Quantity, currency1, trade.Commission, trade.CommissionAsset,
                                                           trade.Quantity,
                                                           currency2, await _marketData.GetHistoricRate("CHF", currency1, trade.Time))
                                );
                        }
                    }
                }
                else
                {
                    Logger.Error(binanceApiResult.Error.Code + " " + binanceApiResult.Error.Message);
                }
            }
            return(trades);
        }
Example #4
0
        public async Task <IEnumerable <CryptoTransaction> > GetTransactionsAsync(Exchange exchange)
        {
            var authenticator = new Authenticator(exchange.PublicKey, exchange.PrivateKey, exchange.Passphrase);
            var client        = new GDAXClient.GDAXClient(authenticator);
            var transactions  = new List <CryptoTransaction>();
            var fills         = await client.FillsService.GetAllFillsAsync();

            foreach (var fill in fills)
            {
                foreach (var fillResponse in fill)
                {
                    var buyCurrency = fillResponse.Side == "buy"
                        ? fillResponse.Product_id.Split('-')[0]
                        : fillResponse.Product_id.Split('-')[1];
                    var sellCurrency = fillResponse.Side == "buy"
                        ? fillResponse.Product_id.Split('-')[1]
                        : fillResponse.Product_id.Split('-')[0];

                    var buyAmount = fillResponse.Side == "buy"
                        ? fillResponse.Size
                        : fillResponse.Size * fillResponse.Price;

                    var sellAmount = fillResponse.Side == "buy"
                        ? fillResponse.Size * fillResponse.Price
                        : fillResponse.Size;

                    transactions.Add(CryptoTransaction.NewTrade(fillResponse.Trade_id.ToString(), fillResponse.Created_at,
                                                                exchange.Id,
                                                                "",
                                                                buyAmount,
                                                                buyCurrency,
                                                                fillResponse.Fee,
                                                                "EUR",
                                                                sellAmount,
                                                                sellCurrency,
                                                                await _marketData.GetHistoricRate("CHF", buyCurrency, fillResponse.Created_at)

                                                                ));
                }
            }

            await Task.Delay(200);

            var accounts = await client.AccountsService.GetAllAccountsAsync();

            await Task.Delay(200);

            foreach (var account in accounts)
            {
                var histories = await client.AccountsService.GetAccountHistoryAsync(account.Id.ToString());

                await Task.Delay(200);

                foreach (var history in histories)
                {
                    var transfers = history.Where(h => h.Type == "transfer");

                    foreach (var transfer in transfers)
                    {
                        if (transfer.Amount > 0)
                        {
                            transactions.Add(CryptoTransaction.NewIn(
                                                 transfer.Id,
                                                 transfer.Created_at,
                                                 exchange.Id,
                                                 "Transfer from Coinbase",
                                                 transfer.Amount,
                                                 account.Currency,
                                                 "Coinbase",
                                                 "GDAX",
                                                 transfer.Id
                                                 ));
                        }
                        else
                        {
                            transactions.Add(CryptoTransaction.NewOut(
                                                 transfer.Id,
                                                 transfer.Created_at,
                                                 exchange.Id,
                                                 "To Coinbase",
                                                 transfer.Amount * -1,
                                                 account.Currency,
                                                 0,
                                                 account.Currency,
                                                 "GDAX",
                                                 "Coinbase",
                                                 transfer.Id
                                                 ));
                        }
                    }
                }
            }

            return(transactions);
        }
Example #5
0
        /// <summary>
        /// Gets the transactions.
        /// </summary>
        /// <param name="exchange">The exchange.</param>
        /// <returns>The transactions.</returns>
        /// <exception cref="NotImplementedException">On incorrect trade type.</exception>
        public async Task <IEnumerable <CryptoTransaction> > GetTransactionsAsync(Model.DbModels.Exchange exchange)
        {
            var api = new Kraken(exchange.PublicKey, exchange.PrivateKey);

            if (assetsCache == null)
            {
                BuildPairCache(api);
                await Task.Delay(2000);
            }

            var transactions = new List <CryptoTransaction>();

            var deposits = api.GetLedgers(null, null, "deposit");

            foreach (var deposit in deposits.Ledger)
            {
                var d        = deposit.Value;
                var key      = d.Refid;
                var dateTime = Helpers.UnixTimeStampToDateTime(d.Time);
                var amount   = d.Amount;
                var currency = assetsCache[d.Asset];
                transactions.Add(CryptoTransaction.NewIn(key, dateTime, exchange.Id, "In", amount, currency, string.Empty, string.Empty, string.Empty));
            }

            await Task.Delay(2000);

            var withdrawals = api.GetLedgers(null, null, "withdrawal");

            foreach (var withdrwaw in withdrawals.Ledger)
            {
                var w        = withdrwaw.Value;
                var key      = w.Refid;
                var dateTime = Helpers.UnixTimeStampToDateTime(w.Time);
                var amount   = -1 * w.Amount;
                var currency = assetsCache[w.Asset];
                var fee      = w.Fee;
                transactions.Add(CryptoTransaction.NewOut(key, dateTime, exchange.Id, "Out", amount, currency, fee, currency, string.Empty, string.Empty, string.Empty));
            }

            await Task.Delay(2000);

            var trades = api.GetTradesHistory(null, true);

            foreach (var trade in trades.Trades)
            {
                var currency1 = assetsCache[trade.Value.Pair.Split('Z').First()];
                var currency2 = assetsCache[trade.Value.Pair.Split('Z').Last()];
                var fee       = trade.Value.Fee;
                var cost      = trade.Value.Cost;
                var volume    = trade.Value.Vol;
                var dateTime  = Helpers.UnixTimeStampToDateTime(trade.Value.Time);
                var fiatRate  = await _marketData.GetHistoricRate("CHF", currency1, dateTime);

                switch (trade.Value.Type)
                {
                case "buy":
                    transactions.Add(
                        CryptoTransaction.NewTrade(
                            trade.Key, dateTime, exchange.Id, "Kraken Buy", volume, currency1, fee, currency2, cost,
                            currency2, fiatRate));

                    break;

                case "sell":
                    transactions.Add(
                        CryptoTransaction.NewTrade(
                            trade.Key, dateTime, exchange.Id, "Kraken Sell", cost, currency2, fee, currency2, volume,
                            currency1, fiatRate));

                    break;

                default: throw new NotImplementedException();
                }
            }

            return(transactions);
        }