Update CoinMarketCap API to V2 | Fix HitBTC balance synchronization

This commit is contained in:
Tanguy Herbron 2018-05-09 01:49:04 +02:00
parent 373a944e41
commit 0927d6629c
7 changed files with 108 additions and 72 deletions

View File

@ -7,6 +7,7 @@ import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.SpannableString;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
@ -20,6 +21,7 @@ import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.nauk.moodl.Activities.SettingsActivity;
import com.nauk.moodl.DataManagers.CurrencyData.Currency;
import com.nauk.moodl.DataManagers.MarketCapManager;
import com.nauk.moodl.DataManagers.PreferencesManager;
import com.nauk.moodl.PlaceholderManager;
@ -197,19 +199,20 @@ public class MarketCapitalization extends Fragment {
private PieDataSet getMarketDominanceDataSet()
{
List<PieEntry> entries = new ArrayList<>();
List<Currency> topCurrencies = marketCapManager.getTopCurrencies();
ArrayList<Integer> colors = new ArrayList<>();
float otherCurrenciesDominance = 0;
float topCurrenciesDominance = 0;
for (String key : marketCapManager.getDominance(preferencesManager.getDefaultCurrency()).keySet())
for(int i = 0; i < topCurrencies.size(); i++)
{
entries.add(new PieEntry(marketCapManager.getDominance(preferencesManager.getDefaultCurrency()).get(key), key));
otherCurrenciesDominance += marketCapManager.getDominance(preferencesManager.getDefaultCurrency()).get(key);
colors.add(dominantCurrenciesColors.get(key));
Log.d("moodl", "Dominance : " + topCurrencies.get(i).getSymbol() + " " + topCurrencies.get(i).getDominance(marketCapManager.getMarketCap()));
entries.add(new PieEntry(topCurrencies.get(i).getDominance(marketCapManager.getMarketCap()), topCurrencies.get(i).getSymbol()));
topCurrenciesDominance += topCurrencies.get(i).getDominance(marketCapManager.getMarketCap());
colors.add(dominantCurrenciesColors.get(topCurrencies.get(i).getSymbol()));
}
entries.add(new PieEntry(100-otherCurrenciesDominance, "Others"));
entries.add(new PieEntry(100-topCurrenciesDominance, "Others"));
colors.add(-12369084);
PieDataSet set = new PieDataSet(entries, "Market Cap Dominance");

View File

@ -490,7 +490,6 @@ public class Summary extends Fragment {
private void loadCurrency(Currency currency)
{
Log.d("moodl", "For " + currency.getSymbol() + " " + (currency.getBalance() * currency.getValue()) + " " + preferencesManager.getMinimumAmount());
if(!currency.getSymbol().equals("USD") && (currency.getBalance() * currency.getValue()) > preferencesManager.getMinimumAmount())
{
currency.setName(balanceManager.getCurrencyName(currency.getSymbol()));

View File

@ -18,7 +18,7 @@ import java.util.List;
public class Currency implements Parcelable {
private int id;
private String tickerId;
private int tickerId;
private String name;
private String symbol;
private double value;
@ -38,6 +38,7 @@ public class Currency implements Parcelable {
private String proofType;
private int totalSupply;
private double marketCapitalization;
private double dominance;
private int rank;
private String startDate;
private List<String> socialMediaLinks;
@ -64,6 +65,13 @@ public class Currency implements Parcelable {
this.symbol = symbol;
}
public Currency(String name, String symbol, int tickerId)
{
this.name = name;
this.symbol = symbol;
this.tickerId = tickerId;
}
//public Currency(int id, String symbol, String name, String algorithm, String proofType, )
public void getTimestampPrice(android.content.Context context, String toSymbol, final PriceCallBack callBack, long timestamp)
@ -396,11 +404,11 @@ public class Currency implements Parcelable {
this.rank = rank;
}
public String getTickerId() {
public int getTickerId() {
return tickerId;
}
public void setTickerId(String tickerId) {
public void setTickerId(int tickerId) {
this.tickerId = tickerId;
}
@ -412,6 +420,11 @@ public class Currency implements Parcelable {
this.startDate = startDate;
}
public float getDominance(float totalMarketCapitalization)
{
return (float) (marketCapitalization / totalMarketCapitalization) * 100;
}
private void updateDayFluctuation()
{
if(historyMinutes != null)
@ -469,7 +482,7 @@ public class Currency implements Parcelable {
dest.writeList(this.historyMinutes);
dest.writeParcelable(this.icon, flags);
dest.writeInt(this.chartColor);
dest.writeString(this.tickerId);
dest.writeInt(this.tickerId);
}
protected Currency(Parcel in) {
@ -484,7 +497,7 @@ public class Currency implements Parcelable {
in.readList(this.historyMinutes, CurrencyDataChart.class.getClassLoader());
this.icon = in.readParcelable(Bitmap.class.getClassLoader());
this.chartColor = in.readInt();
this.tickerId = in.readString();
this.tickerId = in.readInt();
}
public static final Parcelable.Creator<Currency> CREATOR = new Parcelable.Creator<Currency>() {

View File

@ -32,7 +32,7 @@ public class CurrencyDataRetriever {
private String dayHistoryUrl = "https://min-api.cryptocompare.com/data/histoday";
private String priceUrl = "https://min-api.cryptocompare.com/data/pricemultifull?fsyms=";
private String snapshotUrl = "https://www.cryptocompare.com/api/data/coinsnapshotfullbyid/?id=";
private String tickerUrl = "https://api.coinmarketcap.com/v1/ticker/";
private String tickerUrl = "https://api.coinmarketcap.com/v2/ticker/";
private RequestQueue requestQueue;
@ -45,9 +45,9 @@ public class CurrencyDataRetriever {
requestQueue = Volley.newRequestQueue(context);
}
public void updateTickerInfos(String currencyName, final String toSymbol, final CurrencyCallBack callBack)
public void updateTickerInfos(int tickerId, final String toSymbol, final CurrencyCallBack callBack)
{
final String requestUrl = tickerUrl + currencyName + "/?convert=" + toSymbol;
final String requestUrl = tickerUrl + tickerId + "/?convert=" + toSymbol;
StringRequest stringRequest = new StringRequest(Request.Method.GET, requestUrl,
new Response.Listener<String>() {

View File

@ -10,10 +10,13 @@ import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.nauk.moodl.DataManagers.BalanceManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Pattern;
/**
@ -22,9 +25,9 @@ import java.util.regex.Pattern;
public class CurrencyTickerList {
final private static String TICKERLISTURL = "https://api.coinmarketcap.com/v1/ticker/?limit=0";
final private static String TICKERLISTURL = "https://api.coinmarketcap.com/v2/listings/";
private RequestQueue requestQueue;
private LinkedHashMap<String, String> coinTickersHashmap;
private List<Currency> currencyTickerList;
private android.content.Context context;
public CurrencyTickerList(android.content.Context context)
@ -35,7 +38,7 @@ public class CurrencyTickerList {
public void update(final BalanceManager.IconCallBack callBack)
{
coinTickersHashmap = new LinkedHashMap<>();
currencyTickerList = new ArrayList<>();
StringRequest strRequest = new StringRequest(Request.Method.GET, TICKERLISTURL,
new Response.Listener<String>() {
@Override
@ -55,22 +58,19 @@ public class CurrencyTickerList {
requestQueue.add(strRequest);
}
public String getTickerIdForSymbol(String symbol)
public int getTickerIdForSymbol(String symbol)
{
String tickerId = null;
try {
JSONObject jsonObject = new JSONObject(coinTickersHashmap.get(symbol));
tickerId = jsonObject.getString("id");
} catch (JSONException | NullPointerException e) {
switch (e.getMessage())
{
case "Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference":
Log.d("moodl", "Symbol " + symbol + " not supported");
break;
default:
e.printStackTrace();
break;
}
int tickerId = 0;
int i = 0;
while(!currencyTickerList.get(i).equals(symbol) && currencyTickerList.size() < i)
{
i++;
}
if(currencyTickerList.get(i).equals(symbol))
{
tickerId = currencyTickerList.get(i).getTickerId();
}
return tickerId;
@ -78,14 +78,28 @@ public class CurrencyTickerList {
public void processTickerListResult(String response, BalanceManager.IconCallBack callBack)
{
response = response.substring(1, response.length() - 1);
try {
JSONObject dataJsonObject = new JSONObject(response);
JSONArray dataJsonArray = dataJsonObject.getJSONArray("data");
for(int i = 0; i < dataJsonArray.length(); i++)
{
JSONObject currencyJsonObject = dataJsonArray.getJSONObject(i);
currencyTickerList.add(new Currency(currencyJsonObject.getString("name"), currencyJsonObject.getString("symbol"), currencyJsonObject.getInt("id")));
}
} catch (JSONException e) {
e.printStackTrace();
}
/*response = response.substring(16, response.length() - 2);
String[] strTable = response.split(Pattern.quote("},"));
for(int i = 0; i < strTable.length; i++)
{
strTable[i] += "}";
Log.d("moodl", "TICKER " + i + " " + strTable[i]);
try {
JSONObject jsonObject = new JSONObject(strTable[i]);
Log.d("moodl", "TICKER JSON " + i + " " + jsonObject);
switch (jsonObject.getString("symbol"))
{
case "MIOTA":
@ -101,7 +115,7 @@ public class CurrencyTickerList {
} catch (JSONException e) {
e.printStackTrace();
}
}
}*/
callBack.onSuccess();
}

View File

@ -30,7 +30,7 @@ public class HitBtcManager {
private String publicKey;
private String privateKey;
final private String hitBalanceUrl = "https://api.hitbtc.com/api/2/trading/balance";
final private String hitBalanceUrl = "https://api.hitbtc.com/api/2/account/balance";
final private String tradeHistoryUrl = "https://api.hitbtc.com/api/2/history/trades?";
private RequestQueue requestQueue;
private List<String> pairSymbolList;
@ -115,10 +115,12 @@ public class HitBtcManager {
{
try {
JSONObject jsonObject = response.getJSONObject(i);
double available = Double.parseDouble(jsonObject.getString("available"));
double reserved = Double.parseDouble(jsonObject.getString("reserved"));
if(Float.parseFloat(jsonObject.getString("available")) > 0)
if(available > 0 || reserved > 0)
{
balance.add(new Currency(jsonObject.getString("currency"), Double.parseDouble(jsonObject.getString("available"))));
balance.add(new Currency(jsonObject.getString("currency"), available + reserved));
}
} catch (JSONException e) {

View File

@ -1,17 +1,24 @@
package com.nauk.moodl.DataManagers;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.nauk.moodl.DataManagers.CurrencyData.Currency;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;
/**
@ -20,10 +27,10 @@ import java.util.regex.Pattern;
public class MarketCapManager {
private static final String topCurrenciesUrl = "https://api.coinmarketcap.com/v1/ticker/?limit=9&convert=";
private static final String marketCapUrl = "https://api.coinmarketcap.com/v1/global/?convert=";
private static final String topCurrenciesUrl = "https://api.coinmarketcap.com/v2/ticker/?limit=9&convert=";
private static final String marketCapUrl = "https://api.coinmarketcap.com/v2/global/?convert=";
private RequestQueue requestQueue;
private String topRequestResult[];
private List<Currency> topCurrencies;
private long marketCap;
private long dayVolume;
@ -36,6 +43,8 @@ public class MarketCapManager {
{
String requestString = topCurrenciesUrl + toSymbol;
topCurrencies = new ArrayList<>();
StringRequest strRequest = new StringRequest(Request.Method.GET, requestString,
new Response.Listener<String>() {
@Override
@ -86,31 +95,21 @@ public class MarketCapManager {
{
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataJsonObject = jsonObject.getJSONObject("data");
JSONObject quotesJsonObject = dataJsonObject.getJSONObject("quotes");
JSONObject valuesJsonObject = quotesJsonObject.getJSONObject(toSymbol);
marketCap = new BigDecimal(jsonObject.getString("total_market_cap_" + toSymbol.toLowerCase())).longValue();
marketCap = valuesJsonObject.getLong("total_market_cap");
dayVolume = new BigDecimal(jsonObject.getString("total_24h_volume_" + toSymbol.toLowerCase())).longValue();
dayVolume = valuesJsonObject.getLong("total_volume_24h");
} catch (JSONException e) {
e.printStackTrace();
}
}
public HashMap<String, Float> getDominance(String toSymbol)
public List<Currency> getTopCurrencies()
{
HashMap<String, Float> dominance = new HashMap<>();
for(int i = 0; i < topRequestResult.length; i++)
{
try {
JSONObject jsonObject = new JSONObject(topRequestResult[i]);
dominance.put(jsonObject.getString("symbol"), (Float.parseFloat(jsonObject.getString("market_cap_" + toSymbol.toLowerCase())) / marketCap)*100);
} catch (JSONException e) {
e.printStackTrace();
}
}
return dominance;
return topCurrencies;
}
public long getDayVolume()
@ -120,22 +119,28 @@ public class MarketCapManager {
private void processTopCurrencies(String response, String toSymbol)
{
response = response.substring(response.indexOf('[')+1, response.lastIndexOf(']'));
try {
JSONObject masterJsonObject = new JSONObject(response);
topRequestResult = response.split(Pattern.quote("},"));
if(masterJsonObject.keys().hasNext())
{
JSONObject currencyJsonObject = masterJsonObject.getJSONObject(masterJsonObject.keys().next());
Iterator<?> keys = currencyJsonObject.keys();
for(int i = 0; i < topRequestResult.length; i++)
{
topRequestResult[i] += "}";
/*try {
while(keys.hasNext())
{
String key = keys.next().toString();
JSONObject subCurrencyJsonObject = currencyJsonObject.getJSONObject(key);
Currency newCurrency = new Currency(subCurrencyJsonObject.getString("name"), subCurrencyJsonObject.getString("symbol"), subCurrencyJsonObject.getInt("id"));
JSONObject quoteJsonObject = subCurrencyJsonObject.getJSONObject("quotes");
JSONObject symJsonObject = quoteJsonObject.getJSONObject(toSymbol);
newCurrency.setMarketCapitalization(symJsonObject.getDouble("market_cap"));
JSONObject jsonObject = new JSONObject(topRequestResult[i]);
//Log.d("moodl", "Symbol : " + jsonObject.getString("symbol") + " " + jsonObject.getString("rank"));
} catch (JSONException e) {
e.printStackTrace();
}*/
topCurrencies.add(newCurrency);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}