Example #1
0
        private async Task RunExample()
        {
            // Using the ApiCredentials Class
            // Client = new Api(new ApiCredentials(CexUsername, CexApiKey, CexApiSecret));
            // Or not
            // CexClient = new CexApi(CexUsername, CexApiKey, CexApiSecret);
            // ApiCredentials/(Username, ApiKey, ApiSecret) not needed for public functions
            CexClient = new CexApi();

            // Get Ticker Data
            Ticker tickerData = await CexClient.Ticker(SymbolPair.BTC_USD);

            // Get Order Book
            OrderBook orderBook = await CexClient.OrderBook(SymbolPair.BTC_USD);

            // Get Trade history
            IEnumerable <Trade> tradeHistory = await CexClient.TradeHistory(SymbolPair.BTC_USD);

            // ApiCredentials required for user specific calls or "Private Functions"
            CexClient = new CexApi(CexUsername, CexApiKey, CexApiSecret);

            // Get Account Balance
            Balance accountBalance = await CexClient.AccountBalance();

            // Get Open Orders
            IEnumerable <OpenOrder> openOrders = await CexClient.OpenOrders(SymbolPair.LTC_BTC);

            // Place an order
            OpenOrder openOrder = await CexClient.PlaceOrder(
                SymbolPair.BTC_USD,
                new Order
            {
                Amount = 1.00m,
                Price  = 0.04644000m,
                Type   = OrderType.Buy
            });

            // Cancel an order
            bool didSucceed = await CexClient.CancelOrder(openOrder.Id);

            // GHash.IO Example
            GhashClient = new GhashApi(new ApiCredentials(CexUsername, CexApiKey, CexApiSecret));

            // Get Hash Rate
            Hashrate hashrate = await GhashClient.Hashrate();

            // Get Workers Hash Rate
            IEnumerable <KeyValuePair <string, WorkerHashrate> > workerHashRate = await GhashClient.WorkersHashRate();
        }
 public ArbitrageCalculator(CexApi client)
 {
     this.CexClient = client;
 }
        static void Main(string[] args)
        {
            var loggerFactory = new LoggerFactory();

            loggerFactory.AddConsole();
            Console.WriteLine("======================");
            var tradingEngines = new List <ITradingEngine>();

            var useExchange = SupportedExchanges.Unknown;

            while (useExchange == SupportedExchanges.Unknown)
            {
                Console.WriteLine("Type 1 for CEX.IO, Type 2 for GDAX, Type 3 for Bitstamp:");
                useExchange =
                    NumericUtils.GetIntegerValueFromObject(Console.ReadLine()).ParseEnum <SupportedExchanges>();
            }


            Console.Write($"{useExchange.ToString()} API Secret:");
            var secret = Console.ReadLine();

            switch (useExchange)
            {
            case SupportedExchanges.Cex:
                Console.Write("\n CEX Username:"******"\n GDAX Pass phrase:");
                break;

            case SupportedExchanges.Bitstamp:
                Console.Write("\n Bitstamp Client Id:");
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            var username = Console.ReadLine();


            Console.Write($"\n{useExchange.ToString()} API Key:");
            var apiKey = Console.ReadLine();

            Console.Write("\nSlack Notification Webhook Url:");
            var slackWebhook = Console.ReadLine();


            var exchangeCurrency = string.Empty;

            while (exchangeCurrency.IsNullOrEmpty())
            {
                Console.Write($"\n{useExchange.ToString()} Exhcange Base currency name: (default BTC)");
                exchangeCurrency = Console.ReadLine();
                if (Currencies.SupportedCurrencies.Count(i => i == exchangeCurrency) > 0)
                {
                    continue;
                }

                if (exchangeCurrency.IsNullOrEmpty())
                {
                    Console.WriteLine("Default cryptocurrency BTC selected.");
                    exchangeCurrency = Currencies.BTC;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.BackgroundColor = ConsoleColor.White;
                    Console.WriteLine("Invalid currency name. Please try again.");
                    Console.ResetColor();
                    exchangeCurrency = null;
                }
            }

            var targetCurrency = string.Empty;

            while (targetCurrency.IsNullOrEmpty())
            {
                Console.Write($"\n{useExchange.ToString()} Exhcange Target currency name: (default USD)");
                targetCurrency = Console.ReadLine();
                if (Currencies.SupportedCurrencies.Count(i => i == targetCurrency) > 0)
                {
                    continue;
                }

                if (targetCurrency.IsNullOrEmpty())
                {
                    Console.WriteLine("Default target currency USD selected.");
                    targetCurrency = Currencies.USD;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.BackgroundColor = ConsoleColor.White;
                    Console.WriteLine("Invalid currency name. Please try again.");
                    Console.ResetColor();
                    targetCurrency = null;
                }
            }


            var stopLine = 0m;

            while (stopLine <= 0)
            {
                Console.Write("\nSpecify the bottom line value where execution should STOP:");
                stopLine = NumericUtils.GetDecimalValueFromObject(Console.ReadLine());
                if (stopLine > 0)
                {
                    continue;
                }

                Console.ForegroundColor = ConsoleColor.Red;
                Console.BackgroundColor = ConsoleColor.White;
                Console.WriteLine(
                    "Bottom line value must be positive number representing your target currency value. (e.g. 5000 )");
                Console.ResetColor();
            }

            Console.WriteLine(
                $"Minutes of historical orders on {useExchange.ToString()} for buying considerations: (default 3)");
            var publicOrderHistoryForBuyingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (publicOrderHistoryForBuyingDecision <= 0)
            {
                publicOrderHistoryForBuyingDecision = 3;
            }

            Console.WriteLine(
                $"Minutes of historical orders on {useExchange.ToString()} for selling considerations: (default 3)");
            var publicOrderHistoryForSellingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (publicOrderHistoryForSellingDecision <= 0)
            {
                publicOrderHistoryForSellingDecision = 3;
            }

            Console.WriteLine("Minutes of historical account orders for buying considerations: (default 5)");
            var accountOrderHistoryForBuyingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (accountOrderHistoryForBuyingDecision <= 0)
            {
                accountOrderHistoryForBuyingDecision = 5;
            }

            Console.WriteLine("Minutes of historical account orders for selling considerations: (default 5)");
            var accountOrderHistoryForSellingDecision = NumericUtils.GetIntegerValueFromObject(Console.ReadLine());

            if (accountOrderHistoryForSellingDecision <= 0)
            {
                accountOrderHistoryForSellingDecision = 5;
            }

            Console.WriteLine("Minutes change sensitivity ratio in decimal: (default 0.005)");
            var sensitivityRatio = NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (sensitivityRatio <= 0)
            {
                sensitivityRatio = 0.005m;
            }

            Console.WriteLine("Minimum Reserve In Target Currency: (default 0.2)");
            var minimumReservePercentageAfterInitInTargetCurrency =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (minimumReservePercentageAfterInitInTargetCurrency <= 0)
            {
                minimumReservePercentageAfterInitInTargetCurrency = 0.2m;
            }

            Console.WriteLine("Minimum Reserve In Exchange Currency: (default 0.2)");
            var minimumReservePercentageAfterInitInExchangeCurrency =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (minimumReservePercentageAfterInitInExchangeCurrency <= 0)
            {
                minimumReservePercentageAfterInitInExchangeCurrency = 0.2m;
            }

            Console.WriteLine("Order Cap Percentage On Init: (default 0.25)");
            var orderCapPercentageOnInit =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (orderCapPercentageOnInit <= 0)
            {
                orderCapPercentageOnInit = 0.25m;
            }

            Console.WriteLine("Order Cap Percentage After Init: (default 0.3)");
            var orderCapPercentageAfterInit =
                NumericUtils.GetDecimalValueFromObject(Console.ReadLine());

            if (orderCapPercentageAfterInit <= 0)
            {
                orderCapPercentageAfterInit = 0.3m;
            }


            bool autoExecution;

            Console.ForegroundColor = ConsoleColor.White;
            Console.BackgroundColor = ConsoleColor.DarkGreen;
            Console.WriteLine("Automated order execution - Enter 'CONFIRM' to execute order automatically: ");
            Console.ResetColor();
            autoExecution = Console.ReadLine() == "CONFIRM";


            var tradingStrategy = new TradingStrategy
            {
                MinutesOfAccountHistoryOrderForPurchaseDecision     = accountOrderHistoryForBuyingDecision,
                MinutesOfAccountHistoryOrderForSellDecision         = accountOrderHistoryForSellingDecision,
                MinutesOfPublicHistoryOrderForPurchaseDecision      = publicOrderHistoryForBuyingDecision,
                MinutesOfPublicHistoryOrderForSellDecision          = publicOrderHistoryForSellingDecision,
                MinimumReservePercentageAfterInitInTargetCurrency   = minimumReservePercentageAfterInitInTargetCurrency,
                MinimumReservePercentageAfterInitInExchangeCurrency =
                    minimumReservePercentageAfterInitInExchangeCurrency,
                OrderCapPercentageAfterInit = orderCapPercentageAfterInit,
                OrderCapPercentageOnInit    = orderCapPercentageOnInit,
                AutoDecisionExecution       = autoExecution,
                StopLine = stopLine,
                MarketChangeSensitivityRatio    = sensitivityRatio,
                PriceCorrectionFrequencyInHours = 12,
                TradingValueBleedRatio          = 0.1m
            };

            IApi api;

            switch (useExchange)
            {
            case SupportedExchanges.Gdax:
                api = new GdaxApi(apiKey, secret, username, slackWebhook,
                                  loggerFactory.CreateLogger($"GDAX Trading Engine - {exchangeCurrency} - {targetCurrency}"),
                                  tradingStrategy);
                break;

            case SupportedExchanges.Cex:
                api = new CexApi(apiKey, secret, username, slackWebhook,
                                 loggerFactory.CreateLogger($"CEX.IO Trading Engine - {exchangeCurrency} - {targetCurrency}"),
                                 tradingStrategy);
                break;

            case SupportedExchanges.Bitstamp:
                api = new BitstampApi(apiKey, secret, username, slackWebhook,
                                      loggerFactory.CreateLogger($"Bitstamp Trading Engine - {exchangeCurrency} - {targetCurrency}"),
                                      tradingStrategy);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            tradingEngines.Add(new TradingEngine(api, exchangeCurrency, targetCurrency));

            var tasks = new List <Task>();

            foreach (var engine in tradingEngines)
            {
                tasks.Add(Task.Run(async() => await engine.StartAsync()));
            }

            Task.WaitAll(tasks.ToArray());
        }
Example #4
0
        private static void GenerateETHProfitRecordings()
        {
            ProfitRecording pf = new ProfitRecording();

            var luno = LunoApi.GetLunoResult(10.00001M, LunoSymbolEnum.ETHZAR);

            //  decimal bestprice = ((luno.ask.price + luno.bid.price) / 2);

            //var bitlishUSD = BitlishApi.GetBestPrices(BitlsihSymbolEnum.EthUsd, 0.01m);
            //var bitlishEUR = BitlishApi.GetBestPrices(BitlsihSymbolEnum.EthEur, 0.01m);

            var cexUSD = CexApi.GetBestPrices(CEXSymbolEnum.Eth_Usd, 0.01m);
            var cexEUR = CexApi.GetBestPrices(CEXSymbolEnum.Eth_Eur, 0.01m);
            var cexGBP = CexApi.GetBestPrices(CEXSymbolEnum.Eth_Gbp, 0.01m);


            decimal usdzar = 0m;
            decimal eurzar = 0m;
            decimal rubzar = 0m;
            decimal gbpzar = 0m;


            try
            {
                usdzar = CurrencyHelper.ConvertToZAR(1, CurrencyHelper.CurrencyEnum.Usd);
                eurzar = CurrencyHelper.ConvertToZAR(1, CurrencyHelper.CurrencyEnum.Eur);
                rubzar = CurrencyHelper.ConvertToZAR(1, CurrencyHelper.CurrencyEnum.Rub);
                gbpzar = CurrencyHelper.ConvertToZAR(1, CurrencyHelper.CurrencyEnum.Gbp);
            }
            catch
            {
                // failed to get live rates - use latest
                ProfitRecording recEUR = GetLatestByExchangeAndCurrnecy(enExchange.Cex, enCurrency.EUR, "BTC");
                ProfitRecording recUSD = GetLatestByExchangeAndCurrnecy(enExchange.Cex, enCurrency.USD, "BTC");
                ProfitRecording recGBP = GetLatestByExchangeAndCurrnecy(enExchange.Cex, enCurrency.GBP, "BTC");

                eurzar = recEUR.CurrencyToZARExchangeRate;
                usdzar = recUSD.CurrencyToZARExchangeRate;
                gbpzar = recGBP.CurrencyToZARExchangeRate;
            }

            decimal profPerc = 0;

            // Bitlish USD;
            //try
            //{
            //    profPerc = GetProfit(bitlishUSD.ask.price, luno.bid.price, usdzar, 0.4M, 4.84M, 2000);

            //    pf = new ProfitRecording();
            //    pf.Exchange = enExchange.Bitlish;
            //    pf.Currency = enCurrency.USD;
            //    pf.LunoBid = luno.bid.price;
            //    pf.ExchangeAsk = bitlishUSD.ask.price;
            //    pf.CurrencyToZARExchangeRate = usdzar;
            //    pf.ProfitPerc = profPerc;
            //    pf.ArbSymblol = "ETH";
            //    pf.Save();
            //}
            //catch
            //{// duplicate last recording

            //    ProfitRecording pflast = ProfitRecording.GetLatestByExchangeAndCurrnecy(enExchange.Bitlish, enCurrency.USD, "ETH");
            //    pf = new ProfitRecording();
            //    pf.Exchange = pflast.Exchange;
            //    pf.Currency = pflast.Currency;
            //    pf.LunoBid = pflast.LunoBid;
            //    pf.ExchangeAsk = pflast.ExchangeAsk;
            //    pf.CurrencyToZARExchangeRate = pflast.CurrencyToZARExchangeRate;
            //    pf.ProfitPerc = pflast.ProfitPerc;
            //    pf.ArbSymblol = "ETH";
            //    pf.Save();
            //}

            //// Bitlish EUR;
            //try
            //{
            //    profPerc = GetProfit(bitlishEUR.ask.price, luno.bid.price, eurzar, 0.4M, 4.35M, 1500);
            //    pf = new ProfitRecording();
            //    pf.Exchange = enExchange.Bitlish;
            //    pf.Currency = enCurrency.EUR;
            //    pf.LunoBid = luno.bid.price;
            //    pf.ExchangeAsk = bitlishEUR.ask.price;
            //    pf.CurrencyToZARExchangeRate = eurzar;
            //    pf.ProfitPerc = profPerc;
            //    pf.ArbSymblol = "ETH";
            //    pf.Save();
            //}
            //catch
            //{// duplicate last recording
            //    ProfitRecording pflast = ProfitRecording.GetLatestByExchangeAndCurrnecy(enExchange.Bitlish, enCurrency.EUR, "ETH");
            //    pf = new ProfitRecording();
            //    pf.Exchange = pflast.Exchange;
            //    pf.Currency = pflast.Currency;
            //    pf.LunoBid = pflast.LunoBid;
            //    pf.ExchangeAsk = pflast.ExchangeAsk;
            //    pf.CurrencyToZARExchangeRate = pflast.CurrencyToZARExchangeRate;
            //    pf.ProfitPerc = pflast.ProfitPerc;
            //    pf.ArbSymblol = "ETH";
            //    pf.Save();
            //}


            // CEX USD;
            try
            {
                profPerc       = GetProfit(cexUSD.ask.price, luno.bid.price, usdzar, 0.4M, 2.99M, 3000);
                pf             = new ProfitRecording();
                pf.Exchange    = enExchange.Cex;
                pf.Currency    = enCurrency.USD;
                pf.LunoBid     = luno.bid.price;
                pf.ExchangeAsk = cexUSD.ask.price;
                pf.CurrencyToZARExchangeRate = usdzar;
                pf.ProfitPerc = profPerc;
                pf.ArbSymblol = "ETH";
                pf.Save();
            }
            catch
            {// duplicate last recording
                ProfitRecording pflast = ProfitRecording.GetLatestByExchangeAndCurrnecy(enExchange.Cex, enCurrency.USD, "ETH");
                pf             = new ProfitRecording();
                pf.Exchange    = pflast.Exchange;
                pf.Currency    = pflast.Currency;
                pf.LunoBid     = pflast.LunoBid;
                pf.ExchangeAsk = pflast.ExchangeAsk;
                pf.CurrencyToZARExchangeRate = pflast.CurrencyToZARExchangeRate;
                pf.ProfitPerc = pflast.ProfitPerc;
                pf.ArbSymblol = "ETH";
                pf.Save();
            }

            // CEX EUR;
            try
            {
                profPerc       = GetProfit(cexEUR.ask.price, luno.bid.price, eurzar, 0.4M, 2.99M, 3000);
                pf             = new ProfitRecording();
                pf.Exchange    = enExchange.Cex;
                pf.Currency    = enCurrency.EUR;
                pf.LunoBid     = luno.bid.price;
                pf.ExchangeAsk = cexEUR.ask.price;
                pf.CurrencyToZARExchangeRate = eurzar;
                pf.ProfitPerc = profPerc;
                pf.ArbSymblol = "ETH";
                pf.Save();
            }
            catch
            {// duplicate last recording
                ProfitRecording pflast = ProfitRecording.GetLatestByExchangeAndCurrnecy(enExchange.Cex, enCurrency.EUR, "ETH");
                pf             = new ProfitRecording();
                pf.Exchange    = pflast.Exchange;
                pf.Currency    = pflast.Currency;
                pf.LunoBid     = pflast.LunoBid;
                pf.ExchangeAsk = pflast.ExchangeAsk;
                pf.CurrencyToZARExchangeRate = pflast.CurrencyToZARExchangeRate;
                pf.ProfitPerc = pflast.ProfitPerc;
                pf.ArbSymblol = "ETH";
                pf.Save();
            }

            // CEX GBP;
            try
            {
                profPerc       = GetProfit(cexGBP.ask.price, luno.bid.price, gbpzar, 0.4M, 2.99M, 2000);
                pf             = new ProfitRecording();
                pf.Exchange    = enExchange.Cex;
                pf.Currency    = enCurrency.GBP;
                pf.LunoBid     = luno.bid.price;
                pf.ExchangeAsk = cexGBP.ask.price;
                pf.CurrencyToZARExchangeRate = gbpzar;
                pf.ProfitPerc = profPerc;
                pf.ArbSymblol = "ETH";
                pf.Save();
            }
            catch
            { // duplicate last recording
                ProfitRecording pflast = ProfitRecording.GetLatestByExchangeAndCurrnecy(enExchange.Cex, enCurrency.GBP, "ETH");
                pf             = new ProfitRecording();
                pf.Exchange    = pflast.Exchange;
                pf.Currency    = pflast.Currency;
                pf.LunoBid     = pflast.LunoBid;
                pf.ExchangeAsk = pflast.ExchangeAsk;
                pf.CurrencyToZARExchangeRate = pflast.CurrencyToZARExchangeRate;
                pf.ProfitPerc = pflast.ProfitPerc;
                pf.ArbSymblol = "ETH";
                pf.Save();
            }
        }
Example #5
0
        private string get_content(Uri uri, out string extension)
        {
            extension = "";
            // Api Calls
            if (uri.ToString().Contains("/api"))
            {
                string command   = uri.ToString().Split(new string[] { "api" }, StringSplitOptions.None)[1].Substring(1);
                CexApi CexClient = new CexApi(Form1.CexUsername, Form1.CexApiKey, Form1.CexApiSecret);

                switch (command)
                {
                case "ticker":
                    return(Newtonsoft.Json.JsonConvert.SerializeObject(CexClient.Ticker(SymbolPair.XRP_USD).Result));

                    break;

                default:
                    break;
                }

                var orderbook = CexClient.OrderBook(SymbolPair.XRP_USD).Result;

                return(Newtonsoft.Json.JsonConvert.SerializeObject(
                           new
                {
                    // -------------------------------
                    // Cex.Io Api Functions
                    // -------------------------------

                    // -------------------------------
                    // ---- Tag: Public API calls ----
                    // -------------------------------
                    // Currency_limits
                    Ticker = CexClient.Ticker(SymbolPair.XRP_USD).Result,

                    // Tickers_for_all_pairs_by_markets
                    // Last_price
                    // Last_prices_for_given_markets
                    // Converter
                    Chart = CexClient.Chart(SymbolPair.XRP_USD).Result,

                    // Historical_1m_OHLCV_Chart = CexClient.Historical_1m_OHLCV_Chart(SymbolPair.XRP_USD, DateTime.Now.AddDays(-1), "m"),
                    Orderbook =
                        new
                    {
                        Asks = orderbook.Asks.Take(15).Union(orderbook.Asks.Skip(orderbook.Asks.Count() - 5).Take(5)),
                        Bids = orderbook.Bids.Take(15).Union(orderbook.Asks.Skip(orderbook.Bids.Count() - 5).Take(5)),
                        Timestamp = orderbook.Timestamp,
                        buy_total = orderbook.buy_total,
                        sell_total = orderbook.sell_total
                    }
                    ,
                    // Trade_history = CexClient.TradeHistory(SymbolPair.XRP_USD).Result,

                    // --------------------------------
                    // ---- Tag: Private API calls ----
                    // --------------------------------
                    Account_balance = CexClient.AccountBalance().Result,
                    Open_orders = CexClient.OpenOrders(SymbolPair.XRP_USD).Result,
                    // Open_orders_by_pair
                    // Active_order_status
                    // Archived_orders

                    // Cancel_order= CexClient.CancelOrder(new TradeId(0)).Result,
                    // Cancel_all_orders_for_given_pair
                    // Place_order = CexClient.PlaceOrder(SymbolPair.XRP_USD,new Order() { Amount=1, Price=1, Type= OrderType.Buy },null).Result,
                    // Get_order_details
                    // Get_order_transactions
                    // Get_crypto_address
                    // Get_my_fee
                    // Cancel_replace_order
                    // Open_position
                    // Get_position
                    // Open_positions
                    // Close_position
                    // Archived_positions
                    // Get_marginal_fee
                }));
            }
            else // Orher Resource calls
            {
                var path = uri.LocalPath.Substring(1);
                path      = string.IsNullOrWhiteSpace(path) ? this.default_filename : path;
                extension = Path.GetExtension(path);
                return(File.ReadAllText(Path.Combine(this.folder, path)));
            }
        }