TickerTracker optimization
This commit is contained in:
parent
120c4f15fc
commit
0893c4670c
|
|
@ -1,8 +1,6 @@
|
||||||
package com.example.dcav2gui;
|
package com.example.dcav2gui;
|
||||||
|
|
||||||
//import com.google.gson.Gson;
|
|
||||||
import com.google.gson.JsonArray;
|
import com.google.gson.JsonArray;
|
||||||
import com.google.gson.JsonObject;
|
|
||||||
import com.google.gson.JsonParser;
|
import com.google.gson.JsonParser;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
|
@ -15,54 +13,25 @@ import okhttp3.Response;
|
||||||
public class TickerTracker {
|
public class TickerTracker {
|
||||||
private static final String BINANCE_API_BASE_URL = "https://api.binance.com/api/v3/ticker/24hr";
|
private static final String BINANCE_API_BASE_URL = "https://api.binance.com/api/v3/ticker/24hr";
|
||||||
private static final OkHttpClient httpClient = new OkHttpClient();
|
private static final OkHttpClient httpClient = new OkHttpClient();
|
||||||
//private static final Gson gson = new Gson();
|
static int requestDepth = 722;
|
||||||
|
static String requestResolution = "15m";
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves price change percentages for a specific trading pair from Binance.
|
|
||||||
*
|
|
||||||
* @param symbol The trading pair symbol (e.g., "BTCUSDT")
|
|
||||||
* @return PriceChangeData object containing 24h, 7d, and 30d percentage changes
|
|
||||||
* @throws IOException If there's an error connecting to the Binance API
|
|
||||||
*/
|
|
||||||
public static PriceChangeData getPriceChanges(String symbol) throws IOException {
|
public static PriceChangeData getPriceChanges(String symbol) throws IOException {
|
||||||
// Construct the API request URL for 24h change
|
// Construct the API request URL for 24h change
|
||||||
Request request24h = new Request.Builder()
|
|
||||||
.url(BINANCE_API_BASE_URL + "?symbol=" + symbol.toUpperCase(Locale.ROOT))
|
|
||||||
.build();
|
|
||||||
|
|
||||||
// Send 24h request
|
|
||||||
try (Response response24h = httpClient.newCall(request24h).execute()) {
|
|
||||||
if (!response24h.isSuccessful()) {
|
|
||||||
throw new IOException("Unexpected code " + response24h);
|
|
||||||
}
|
|
||||||
String responseBody24h = response24h.body().string();
|
|
||||||
JsonObject jsonResponse = JsonParser.parseString(responseBody24h).getAsJsonObject();
|
|
||||||
|
|
||||||
// Extract current price
|
|
||||||
double currentPrice = jsonResponse.has("lastPrice")
|
|
||||||
? jsonResponse.get("lastPrice").getAsDouble()
|
|
||||||
: 0.0;
|
|
||||||
|
|
||||||
// Extract 24h percentage change
|
|
||||||
double priceChangePercent24h = jsonResponse.has("priceChangePercent")
|
|
||||||
? jsonResponse.get("priceChangePercent").getAsDouble()
|
|
||||||
: 0.0;
|
|
||||||
|
|
||||||
// Fetch historical data for 7d and 30d changes
|
|
||||||
Request historicalRequest = new Request.Builder()
|
Request historicalRequest = new Request.Builder()
|
||||||
.url("https://api.binance.com/api/v3/klines?symbol=" + symbol.toUpperCase(Locale.ROOT) + "&interval=1d&limit=30")
|
.url("https://api.binance.com/api/v3/klines?symbol=" + symbol.toUpperCase(Locale.ROOT) + "&interval=15m&limit=722")
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
// Send historical data request
|
|
||||||
try (Response historicalResponse = httpClient.newCall(historicalRequest).execute()) {
|
try (Response historicalResponse = httpClient.newCall(historicalRequest).execute()) {
|
||||||
if (!historicalResponse.isSuccessful()) {
|
if (!historicalResponse.isSuccessful()) {
|
||||||
throw new IOException("Unexpected code " + historicalResponse);
|
throw new IOException("Unexpected code " + historicalResponse);
|
||||||
}
|
}
|
||||||
String historicalResponseBody = historicalResponse.body().string();
|
String historicalResponseBody = historicalResponse.body().string();
|
||||||
|
|
||||||
// Calculate 7d and 30d percentage changes
|
double currentPrice = getCurrentPrice(historicalResponseBody);
|
||||||
double priceChangePercent7d = calculatePercentageChange(historicalResponseBody, 7);
|
double priceChangePercent24h = calculatePercentageChange(historicalResponseBody, 24);
|
||||||
double priceChangePercent30d = calculatePercentageChange(historicalResponseBody, 30);
|
double priceChangePercent7d = calculatePercentageChange(historicalResponseBody, 7*24);
|
||||||
|
double priceChangePercent30d = calculatePercentageChange(historicalResponseBody, 30*24);
|
||||||
|
|
||||||
// Return the price change data
|
// Return the price change data
|
||||||
return new PriceChangeData(
|
return new PriceChangeData(
|
||||||
|
|
@ -74,28 +43,34 @@ public class TickerTracker {
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// Calculates the percentage change
|
private static double getCurrentPrice(String jsonKlineData) {
|
||||||
private static double calculatePercentageChange(String jsonKlineData, int days) {
|
|
||||||
try {
|
try {
|
||||||
// Parse the kline data
|
// Parse the kline data
|
||||||
JsonArray klines = JsonParser.parseString(jsonKlineData).getAsJsonArray();
|
JsonArray klines = JsonParser.parseString(jsonKlineData).getAsJsonArray();
|
||||||
|
return klines.get(requestDepth-1).getAsJsonArray().get(4).getAsDouble();
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.err.println("Error processing klines for price: " + e.getMessage());
|
||||||
|
return 0.0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculates the percentage change
|
||||||
|
private static double calculatePercentageChange(String jsonKlineData, int hours) {
|
||||||
|
try {
|
||||||
|
JsonArray klines = JsonParser.parseString(jsonKlineData).getAsJsonArray();
|
||||||
|
|
||||||
// Ensure we have enough data
|
// Ensure we have enough data
|
||||||
if (klines == null || klines.size() < days) {
|
if (klines == null || klines.size() < hours) {
|
||||||
return 0.0;
|
return 0.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Get the opening price of the first day in the period
|
int backwards = 721;
|
||||||
// Kline data structure: [Open time, Open, High, Low, Close, Volume, Close time, Quote asset volume, Number of trades, Taker buy base asset volume, Taker buy quote asset volume, Ignore]
|
double currentPrice = klines.get(backwards).getAsJsonArray().get(4).getAsDouble();
|
||||||
double firstOpenPrice = klines.get(0).getAsJsonArray().get(1).getAsDouble();
|
double periodEndPrice = klines.get(backwards-hours-1).getAsJsonArray().get(1).getAsDouble();
|
||||||
|
|
||||||
// Get the closing price of the last day in the period
|
|
||||||
double lastClosePrice = klines.get(days - 1).getAsJsonArray().get(4).getAsDouble();
|
|
||||||
|
|
||||||
// Calculate percentage change
|
// Calculate percentage change
|
||||||
return ((lastClosePrice - firstOpenPrice) / firstOpenPrice) * 100;
|
return ((currentPrice-periodEndPrice) / periodEndPrice * 100);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
System.err.println("Error calculating percentage change: " + e.getMessage());
|
System.err.println("Error calculating percentage change: " + e.getMessage());
|
||||||
return 0.0;
|
return 0.0;
|
||||||
|
|
@ -126,10 +101,5 @@ public class TickerTracker {
|
||||||
public double getPriceChangePercent7d() { return priceChangePercent7d; }
|
public double getPriceChangePercent7d() { return priceChangePercent7d; }
|
||||||
public double getPriceChangePercent30d() { return priceChangePercent30d; }
|
public double getPriceChangePercent30d() { return priceChangePercent30d; }
|
||||||
|
|
||||||
// @Override
|
|
||||||
// public String toString() {
|
|
||||||
// return String.format("Symbol: %s\nPrice: %.2f%%\n24h Change: %.2f%%\n7d Change: %.2f%%\n30d Change: %.2f%%",
|
|
||||||
// symbol, currentPrice, priceChangePercent24h, priceChangePercent7d, priceChangePercent30d);
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -137,6 +137,37 @@ public class HomeFragment extends Fragment {
|
||||||
profitsToday.setText(R.string.profits_today_example);
|
profitsToday.setText(R.string.profits_today_example);
|
||||||
profitsThisMonth.setText(R.string.profits_this_month_example);
|
profitsThisMonth.setText(R.string.profits_this_month_example);
|
||||||
|
|
||||||
|
|
||||||
|
//Load cached values
|
||||||
|
//Prices
|
||||||
|
pricePair1.setText(R.string.default_price_ticker_1);
|
||||||
|
pricePair2.setText(R.string.default_price_ticker_2);
|
||||||
|
pricePair3.setText(R.string.default_price_ticker_3);
|
||||||
|
|
||||||
|
pricePair124hPercentage.setText(R.string.percentage_example);
|
||||||
|
pricePair17dPercentage.setText(R.string.percentage_example);
|
||||||
|
pricePair130dPercentage.setText(R.string.percentage_example);
|
||||||
|
|
||||||
|
pricePair224hPercentage.setText(R.string.percentage_example);
|
||||||
|
pricePair27dPercentage.setText(R.string.percentage_example);
|
||||||
|
pricePair230dPercentage.setText(R.string.percentage_example);
|
||||||
|
|
||||||
|
pricePair324hPercentage.setText(R.string.percentage_example);
|
||||||
|
pricePair37dPercentage.setText(R.string.percentage_example);
|
||||||
|
pricePair330dPercentage.setText(R.string.percentage_example);
|
||||||
|
|
||||||
|
pricePair124hPercentage.setTextColor(Color.GREEN);
|
||||||
|
pricePair17dPercentage.setTextColor(Color.GREEN);
|
||||||
|
pricePair130dPercentage.setTextColor(Color.GREEN);
|
||||||
|
|
||||||
|
pricePair224hPercentage.setTextColor(Color.GREEN);
|
||||||
|
pricePair27dPercentage.setTextColor(Color.GREEN);
|
||||||
|
pricePair230dPercentage.setTextColor(Color.GREEN);
|
||||||
|
|
||||||
|
pricePair324hPercentage.setTextColor(Color.GREEN);
|
||||||
|
pricePair37dPercentage.setTextColor(Color.GREEN);
|
||||||
|
pricePair330dPercentage.setTextColor(Color.GREEN);
|
||||||
|
|
||||||
//Exchange status
|
//Exchange status
|
||||||
exchange1Status.setImageResource(R.drawable.ic_green_circle_48);
|
exchange1Status.setImageResource(R.drawable.ic_green_circle_48);
|
||||||
exchange2Status.setImageResource(R.drawable.ic_green_circle_48);
|
exchange2Status.setImageResource(R.drawable.ic_green_circle_48);
|
||||||
|
|
@ -189,7 +220,7 @@ public class HomeFragment extends Fragment {
|
||||||
log4Content.setText(R.string.log_example);
|
log4Content.setText(R.string.log_example);
|
||||||
|
|
||||||
// Let's fetch prices
|
// Let's fetch prices
|
||||||
fetchAndDisplayPriceData();
|
//fetchAndDisplayPriceData();
|
||||||
|
|
||||||
// Setup task
|
// Setup task
|
||||||
handler = new Handler();
|
handler = new Handler();
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue