Example #1
0
        public IEnumerable <CoinInformation> GetCoinInformation(string userAgent = "")
        {
            ApiWebClient client = new ApiWebClient();

            if (!string.IsNullOrEmpty(userAgent))
            {
                client.Headers.Add("user-agent", userAgent);
            }

            string apiUrl = GetApiUrl();

            string jsonString = client.DownloadFlakyString(apiUrl);

            JArray jsonArray = JArray.Parse(jsonString);

            List <CoinInformation> result = new List <CoinInformation>();

            foreach (JToken jToken in jsonArray)
            {
                CoinInformation coinInformation = new CoinInformation();
                coinInformation.PopulateFromJson(jToken);
                if (coinInformation.Difficulty > 0)
                {
                    //only add coins with valid info since the user may be basing
                    //strategies on Difficulty
                    result.Add(coinInformation);
                }
            }

            return(result);
        }
        /// <summary>
        /// Utility method: GetCoinSnapshotByID - Invoke CryptoCompare.com API's CoinSnapshotFullById call to
        /// obtain the additional elements (i.e. current blocks, block reward, total coins mined, etc.) that
        /// are not provided by CryptoCompare.com API's coinlist call, given the numeric id of a coin
        /// </summary>
        /// <param name="client"></param>
        /// <param name="coinInformation"></param>
        /// <returns>void</returns>
        private void GetCoinSnapshotByID(ApiWebClient client, CoinInformation coinInformation)
        {
            string coinSnapshotIDParam = "";

            // Obtain numeric id of the coin whose full record is passed in as coinInformation parameter
            coinSnapshotIDParam = coinInformation.Id;

            // Build URL string for the CoinSnapshotFullById CryptoCompare.com API call
            string apiUrl = BuildApiUrlByID(coinSnapshotIDParam, "CoinSnapshotByID");

            // Invoke CryptoCompare.com API's CoinSnapshotFullById call URL, then deserialize result and populate
            // the additional fields provided by this API call into the coinInformation coin record
            string json = client.DownloadAsString(apiUrl);

            try
            {
                RootObjectCoinSnapshot  coinsnapshotset = JsonConvert.DeserializeObject <RootObjectCoinSnapshot>(json);
                GeneralCoinSnapshotData coinSnapshot    = new GeneralCoinSnapshotData();
                coinSnapshot = coinsnapshotset.Data.General;
                coinInformation.PopulateFromJson(coinSnapshot);
            }
            catch (Exception e)
            {
                string errorMsg = e.Message;
            }
        }
Example #3
0
        public IEnumerable <CoinInformation> GetCoinInformation(string userAgent = "")
        {
            WebClient client = new ApiWebClient();

            if (!string.IsNullOrEmpty(userAgent))
            {
                client.Headers.Add("user-agent", userAgent);
            }

            string apiUrl = GetApiUrl();

            string jsonString = String.Empty;

            try
            {
                jsonString = client.DownloadString(apiUrl);
            }
            catch (WebException ex)
            {
                if ((ex.Status == WebExceptionStatus.ProtocolError) &&
                    (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.BadGateway))
                {
                    //try again 1 more time if error 502
                    Thread.Sleep(750);
                    jsonString = client.DownloadString(apiUrl);
                }
                else
                {
                    throw;
                }
            }

            JArray jsonArray = JArray.Parse(jsonString);

            List <CoinInformation> result = new List <CoinInformation>();

            foreach (JToken jToken in jsonArray)
            {
                CoinInformation coinInformation = new CoinInformation();
                coinInformation.PopulateFromJson(jToken);
                if (coinInformation.Difficulty > 0)
                {
                    //only add coins with valid info since the user may be basing
                    //strategies on Difficulty
                    result.Add(coinInformation);
                }
            }

            return(result);
        }
        /// <summary>
        /// Utility method: GetCoinPriceMulti - populates Price and Market Cap fields for result set of coin
        /// records; the coin symbols in the result set are passed in as parameters
        /// Note: if GetCoinPriceMulti method is being invoked from GetCoinInformation API method, Market Cap
        /// will always be 0 - see comment in GetCoinInformation method; only when GetCoinPriceMulti method is
        /// invoked from GetCoinInformationWithSnapshot, can the Market Cap be calculated
        /// </summary>
        /// <param name="client"></param>
        /// <param name="apiUrlInputParams"></param>
        /// <returns>void</returns>
        private void GetCoinPriceMulti(ApiWebClient client, string apiUrlInputParams)
        {
            // Build URL string for the Pricemulti CryptoCompare.com API call
            string apiUrl = BuildApiUrlWithBasicParams(apiUrlInputParams, "Pricemulti", true, true);

            // Invoke CryptoCompare.com API's pricemulti call URL, then deserialize result
            // JSON string will be in the following format: {"ETH":{"USD":226.63},"DASH":{"USD":187.87}}
            string json = client.DownloadAsString(apiUrl);

            // Reformat returned JSON string into format that can be deserialized into RootObjectPriceMulti object
            // Also make a copy of the returned JSON string, strip off leading "{" &  final "}", and split it into
            // an array of Price results per coin
            string remainingJson = json.Remove(0, 1);

            remainingJson = remainingJson.Remove(remainingJson.Length - 1, 1);
            json          = "{\"Data\":" + json;
            json         += "}";
            var coinpricelist = JsonConvert.DeserializeObject <RootObjectPriceMulti>(json);

            string[] splitJson = remainingJson.Split(',');

            int splitIndex = 0;

            // Loop through the Price results array, incrementing splitIndex as the loop iteration counter
            foreach (CoinPrice coinPrice in coinpricelist.Data.Values)
            {
                CoinInformation coinInformation = new CoinInformation();

                // For each array element (i.e. each coin's Price result), the coin symbol is the portion before
                // the first ":", minus the leading & final "\" that appear in the string as escape characters
                string fromCoin = splitJson[splitIndex].Split(':')[0];
                fromCoin = fromCoin.Trim('\"');

                // Select the coin being processed by current iteration of the for loop in the original coin
                // information result set and populate the Price and Market Cap fields in this coin's record
                coinInformation = _coinInfoResultSet.Find(x => x.Symbol.Equals(fromCoin));
                coinInformation.PopulateFromJson(coinPrice);

                splitIndex += 1;
            }
        }
        public IEnumerable <CoinInformation> GetCoinInformation(string userAgent = "")
        {
            WebClient client = new ApiWebClient();

            if (!string.IsNullOrEmpty(userAgent))
            {
                client.Headers.Add("user-agent", userAgent);
            }

            string  apiUrl     = GetApiUrl();
            string  jsonString = client.DownloadString(apiUrl);
            JObject jsonObject = JObject.Parse(jsonString);

            string resultStatus = jsonObject.Value <string>("status");

            if (!resultStatus.Equals("success", StringComparison.OrdinalIgnoreCase))
            {
                throw new CoinApiException(resultStatus);
            }

            List <CoinInformation> result = new List <CoinInformation>();

            JArray jsonArray = jsonObject.Value <JArray>("Data");

            foreach (JToken jToken in jsonArray)
            {
                CoinInformation coinInformation = new CoinInformation();
                coinInformation.PopulateFromJson(jToken);
                if (coinInformation.Difficulty > 0)
                {
                    //only add coins with valid info since the user may be basing
                    //strategies on Difficulty
                    result.Add(coinInformation);
                }
            }

            CalculateProfitability(result);

            return(result);
        }
        public IEnumerable <CoinInformation> GetCoinInformation(string userAgent = "")
        {
            ApiWebClient client = new ApiWebClient();

            if (!string.IsNullOrEmpty(userAgent))
            {
                client.Headers.Add("user-agent", userAgent);
            }

            //get GPU coin info (scrypt, X11, etc)
            string jsonString = client.DownloadString(GetApiUrl());

            Data.ApiResponse apiResponse = JsonConvert.DeserializeObject <Data.ApiResponse>(jsonString);

            //merge in ASIC coin info (sha-256, scrypt, etc)
            jsonString = client.DownloadString(GetAsicApiUrl());
            Data.ApiResponse asicApiResponse = JsonConvert.DeserializeObject <Data.ApiResponse>(jsonString);
            foreach (string coinName in asicApiResponse.Coins.Keys)
            {
                apiResponse.Coins[coinName] = asicApiResponse.Coins[coinName];
            }

            List <CoinInformation> result = new List <CoinInformation>();

            foreach (string coinName in apiResponse.Coins.Keys)
            {
                CoinInformation coinInformation = new CoinInformation();
                coinInformation.Name = coinName;
                coinInformation.PopulateFromJson(apiResponse.Coins[coinName]);
                if (coinInformation.Difficulty > 0)
                {
                    //only add coins with valid info since the user may be basing
                    //strategies on Difficulty
                    result.Add(coinInformation);
                }
            }

            return(result);
        }
Example #7
0
        public IEnumerable <CoinInformation> GetCoinInformation(string userAgent            = "",
                                                                BaseCoin profitabilityBasis = BaseCoin.Bitcoin)
        {
            WebClient client = new ApiWebClient();

            if (!string.IsNullOrEmpty(userAgent))
            {
                client.Headers.Add("user-agent", userAgent);
            }

            string apiUrl = GetApiUrl(profitabilityBasis);

            string jsonString = client.DownloadString(apiUrl);

            JObject jsonObject = JObject.Parse(jsonString);

            if (!jsonObject.Value <bool>("Success"))
            {
                throw new CoinApiException(jsonObject.Value <string>("Message"));
            }

            JArray jsonArray = jsonObject.Value <JArray>("Data");

            List <CoinInformation> result = new List <CoinInformation>();

            foreach (JToken jToken in jsonArray)
            {
                CoinInformation coinInformation = new CoinInformation();
                coinInformation.PopulateFromJson(jToken);
                if (coinInformation.Difficulty > 0)
                {
                    //only add coins with valid info since the user may be basing
                    //strategies on Difficulty
                    result.Add(coinInformation);
                }
            }

            return(result);
        }
        /// <summary>
        /// API method: GetCoinInformationWithSnapshot - returns result set of complete coin records with all
        /// fields returned by GetCoinInformation plus additional fields, i.e. current blocks, block reward,
        /// total coins mined, reward reduction, estimated block time, hash rate per second, and market cap (note:
        /// whenever any of these fields are unavailable for a certain coin, they are returned as 0 or blank,
        /// depending on data type).  This method is only available with a comma-separated list of coins passed
        /// in as a parameter (e.g. "BTC,ETH,UIS"), because CryptoCompare's CoinSnapshotFullById call that
        /// provides this info requires a coin ID parameter, and calling it for the full result set of all coins
        /// in GetCoinInformation result set one by one would result in unacceptably slow performance.
        /// 2 overloads: 1) First parameter is a comma-separated string; 2) First parameter is a List of strings
        /// Parameters below are for overload #2
        /// </summary>
        /// <param name="targetCoinSymbolList"></param>
        /// <param name="userAgent"></param>
        /// <returns>result set of coin records of type IEnumerable; null if cannot be obtained</returns>
        public IEnumerable <CoinInformation> GetCoinInformationWithSnapshot(List <string> targetCoinSymbolList,
                                                                            string userAgent = "")
        {
            List <CoinInformation> result = new List <CoinInformation>();

            // Clear out member variable that will store the result set from any previous call to this API
            if (_coinInfoResultSet.Count > 0)
            {
                _coinInfoResultSet.RemoveRange(0, _coinInfoResultSet.Count - 1);
            }

            ApiWebClient client = new ApiWebClient();

            if (!string.IsNullOrEmpty(userAgent))
            {
                client.Headers.Add("user-agent", userAgent);
            }

            // Call special no-parameter overload of GetApiUrl method to build CryptoCompare.com API's
            // coinlist call URL
            string apiUrl = GetApiUrl();

            // Invoke CryptoCompare.com API's coinlist call URL, then deserialize result
            string json     = client.DownloadAsString(apiUrl);
            var    coinlist = JsonConvert.DeserializeObject <RootObjectCoinList>(json);

            string apiUrlInputParams = "";

            // Process each coin in result set to obtain both the elements provided by coinlist API call and
            // the additional elements provided by the CoinSnapshotFullById API call.
            // Additionally, build parameter string of coin names for the separate pricemulti API call.
            foreach (CoinInfo coin in coinlist.Data.Values)
            {
                CoinInformation coinInformation = new CoinInformation();

                // Obtain basic elements provided by coinlist API call, i.e. numeric coin id, symbol, name,
                // total coin supply, etc. for the coin being processed by the current iteration of the for loop
                coinInformation.PopulateFromJson(coin);

                // Select the coin being processed by current iteration of the for loop for further processsing
                // only if this coin is in the targetCoinSymbolList
                if (targetCoinSymbolList.Exists(x => x.Equals(coinInformation.Symbol)))
                {
                    // Invoke GetCoinSnapshotByID to obtain the additional elements provided by the
                    // CoinSnapshotFullById API call (i.e. current blocks, block reward, total coins mined, etc.)
                    GetCoinSnapshotByID(client, coinInformation);

                    // Add current coin's symbol to the parameter string for the pricemulti API call.
                    apiUrlInputParams += coinInformation.Symbol;
                    apiUrlInputParams += ",";
                    _coinInfoResultSet.Add(coinInformation);
                }
            }

            // Obtain coin price and market cap for each coin in the result set by making a pricemulti API call
            // for the list of coins in the comma-separated input parameter
            GetCoinPriceMulti(client, apiUrlInputParams);

            result = _coinInfoResultSet;
            return(result);
        }
        /// <summary>
        /// API method: GetCoinInformation - returns result set of all coin records with fields including:
        /// numeric coin id, symbol, name, algorithm, proof type, total coin supply, and price (note: whenever
        /// any of these fields are unavailable for a certain coin, they are returned as 0 or blank, depending
        /// on data type)
        /// </summary>
        /// <param name="userAgent"></param>
        /// <returns>result set of coin records of type IEnumerable; null if cannot be obtained</returns>
        public IEnumerable <CoinInformation> GetCoinInformation(string userAgent = "")
        {
            ApiWebClient client = new ApiWebClient();

            if (!string.IsNullOrEmpty(userAgent))
            {
                client.Headers.Add("user-agent", userAgent);
            }

            // Clear out member variable that will store the result set from any previous call to this API
            if (_coinInfoResultSet.Count > 0)
            {
                _coinInfoResultSet.RemoveRange(0, _coinInfoResultSet.Count - 1);
            }

            // Call special no-parameter overload of GetApiUrl method to build CryptoCompare.com API's
            // coinlist call URL
            string apiUrl = GetApiUrl();

            // Invoke CryptoCompare.com API's coinlist call URL, then deserialize result
            string json     = client.DownloadAsString(apiUrl);
            var    coinlist = JsonConvert.DeserializeObject <RootObjectCoinList>(json);

            int           count = 0;
            int           index = 0;
            List <string> apiUrlInputParamsArray = new List <string>();

            apiUrlInputParamsArray.Add("");

            // Process each coin in result set to obtain elements such as symbol, name, total coin supply, etc.
            // Additionally, build parameter array of coin names for the separate pricemulti API call.
            // The parameter array is actually a list of arrays, to set up for multiple calls to pricemulti
            // and avoid a single performance-hindering call with hundreds of coin parameters.
            // Please refer to MAX_PARAM_COUNT documentation above.
            foreach (CoinInfo coin in coinlist.Data.Values)
            {
                count += 1;
                CoinInformation coinInformation = new CoinInformation();
                coinInformation.PopulateFromJson(coin);
                apiUrlInputParamsArray[index] += coinInformation.Symbol;
                apiUrlInputParamsArray[index] += ",";
                _coinInfoResultSet.Add(coinInformation);
                if (count == MAX_PARAM_COUNT)
                {
                    index += 1;
                    apiUrlInputParamsArray.Add("");
                    count = 0;
                }
            }

            // Obtain coin price for each coin in the result set by making CryptoCompare.com API's pricemulti
            // calls for each array of coins in the input parameter list of arrays
            // Note: method GetCoinPriceMulti calculates the Market Cap in addition to obtaining the price;
            // however, since CryptoCompare.com API's coinlist call does not return Total Coins Mined, this
            // calculation of Market Cap will always come out to 0 here; therefore, Market Cap can only be
            // provided by GetCoinPriceMulti calls from GetCoinInformationWithSnapshot API method
            for (int ind = 0; ind < apiUrlInputParamsArray.Count; ind++)
            {
                GetCoinPriceMulti(client, apiUrlInputParamsArray[ind]);
            }

            List <CoinInformation> result = new List <CoinInformation>();

            result = _coinInfoResultSet;
            return(result);
        }